Object C
                 Bit Academy
Object C
               •   C                    80
                          Brad J. Cox

               •   1980                      NextStep


               •   Object C
•           :       (
                   ,           )

               •       :
•
               •
                                                    0


               •
                                   .

               • Car *myCar = [[Car alloc] init];
•                : alloc (call retain)

               •                : release

               •   Car *myCar = [[Car alloc] init];

               •   printf(“The retain count is %dn”, [myCar retainCount]);

               •   [myCar release];

               •   printf(“Retain count is now %dn”, [myCar retainCount]); //error

               •                                        ,         retain      release
,           ,

               •          :

               •          :


               •          :

               •              : initWithName: andModel:
                   andYear: (                     )
•
               •
                   .
•   .h

               •             -

               •        +

               •        .m
• .m (                                                                           )
               #import “Car.h”
               @implementation Car

               -(id) init                    The init method defined in the NSObject class
                                               does no initialization, it simply returns self
               {
                   self = [super init];
                   if(!self) = return nil;

                   make = nil;
                   model = nil;
                   year = 1901;
                   return self;
               }
[obj method_name];
          obj :
          method_name          .
•   +       . +(NSString *) motto;

               •   [   _           _        ]

               •
                   •
                   •

                   •
+ (NSString *) motto
               {
                  return (@”Ford Prefects are Mostly Harmless”);
               }

               [Car motto];


                                                                   .
               [UIApplication sharedApplication];
               [UIDevice currentDevice];



               [[NSArray alloc] init];
               [NSArray array]; ->
                                                                       .
•
               •
                    C

               •            -C           factory,   factory
                   method

               •                                              .

               •

               •   NSObject      class
                      .
alloc
               class
•   +
               •

               •
•            -C
                   static


               •
               •                 ,
for/in                                   for loop

               NSArray *colors = [NSArray arrayWithObjects:@”Blacks”,
               @”Silver”, @”Gray”, nil];
               for (NSString *color in colors)
               {
                  printf(“Consider buying a %s car”, [color UTF8String]);
               }
NSObject


                          NSArray     NSString    UIResponder

                                                   UIView


                                     UILabel      UIControl

                                    UITextField    UISlider




               object C                                             .

                                                   .
                                                                .
NSObject

               •   -C

                   (     ,          ,
                   ,          )

               •         NSObject
                               .
•   NSLog : C   printf                , stdout
                   stderr               . NSString


               •   NSString    @”          ”                    .

               •   NSLog


               •   NSLog(@”Make %@”, make);
Scope of Instance Variables
               Directive
               Meaning
               @private
               The instance variable is accessible only within the class that declares it.


               @protected
               The instance variable is accessible within the class that declares it and within                                  .
               classes that inherit it.
                All instance variables without an explicit scope directive have @protected        @interface Worker : NSObject
               scope.
                                                                                                  {
               @public
                                                                                                      char *name;
               The instance variable is accessible everywhere.
                                                                                                  @private

               @package                                                                               int age;
               Using the modern runtime, an @package instance variable has @public scope
               inside the executable image that implements the class, but acts like @private          char *evaluation;
               outside.
                                                                                                  @protected
               The @package scope for Objective-C instance variables is analogous to
               private_extern for C variables and functions.                                          id job;
               Any code outside the class implementation’s image that tries to use the
               instance variable gets a link error.                                                   float wage;
               This scope is most useful for instance variables in framework classes, where
                                                                                                  @public
               @private may be too restrictive but @protected or @public too permissive.
                                                                                                      id boss;

                                                                                                  }

                                                                                                  protected: name, job, wage
                                                                                                  private: age, evaluation
                                                                                                  public: boss
•
               •
               •   @property(attributes) type name;

               •   attributes : assign, retain, copy

               •   retain, copy : release message sent to the previous
                   value

               •   attributes: readonly, readwrite(       readwrite)

               •   attribute : nonatomic (default is atomic)
dot syntax
               •            .            =

               •                                       .
                                                 ,
                                         .

               •   property-synthesize
                                             .

               •                     retain, release
retained property
               • property (retain) NSArray *colors;
               • @synthesize colors;
               •
                                                            .

               • self.colors = [NSArray arrayWithObjects:
                 @”Gray”, @”Silver”, @”Black”];
•                                     retain
                   count       1
                                   1                     0
                                           dealloc
                                       .

               •
                           .
•    alloc init
                                   1        .

                -(void) leakyMethod
                {
                    NSArray *array = [[NSArray alloc] init];
                }
                -(void) properMethod
                {
                    NSArray *array = [[NSArray alloc] init];
                    [array release];
                }
                 -(void) anotherProperMethod
                 {
                     NSArray *array = [[[NSArray alloc] init] autorelease];
                     }
               -(void) yetAnotherProperMethod
               {
                   NSArray *array = [NSArray array]; //                       .
                   }
•                             release


               • Car *car = [[[Car alloc] init] autorelease]
               • Car *car = [Car car];
               •   + (Car *) car
                   {
                                                        class method, convenience method

                      return [[[Car alloc] init] autorelease];
                   }
•
               •
               •
                   1   .
• property        retain


               • @property (retain) NSArray *colors
               •
Retain Count
                 When you create an object, it has a retain
                 count of 1.
               • When you send an object a retain
                 message, its retain count is incremented by
                 1.
               • When you send an object a release
                 message, its retain count is decremented by
                 1.
               • When you send an object a autorelease
                 message, its retain count is decremented by
                 1 at some stage in the future.
Autorelease

               •              release
                   release

               • release pool           autorelease
                         release pool
                   release

               •
•
               •
               •                                                                  .

               •
                   •   To declare methods that others are expected to implement

                   •   To declare the interface to an object while concealing its class

                   •   To capture similarities among classes that are not hierarchically related
protocol
               protocol_A.h

               #import <Foundation/Foundation.h>

               @protocol Protocol_A
                - methodA;
                @required
                  - methodB;
                @optional
                  - methodC;
               @end
Toy.h
               #import “protocol_A.h”

               @interface Toy:NSObject <protocol_A>
               {
                 NSString * name;
               }
               @end
Toy.m
               #import “protocol_A.h”

               @implementation Toy
               - method_A
               {
                 printf(“method_A implemented in Toyn”);
               }
               - method_B
               {
                 printf(“method_B implemented in Toyn”);

               }
               @end
main.m
               #import <Foundation/Foundation.h>
               #import “Toy.h”

               main()
               {
                 Toy *toy_object = [[Toy alloc] init];
                 [toy_object method_A];
                 [toy_object method_B];

                   [toy_object release];
               }
•
               •                .

               •                                         .

               •                (.h)     (.m)                .

               •   +   .h           +           .m

               •            +           .m           .
•                          ,

               •   Subclass

               •                              .
                              .

                   -              ,


                   -

                   -

                   -                  .

                   -                              .
ClassName+CategoryName.h

               #import "ClassName.h"



               @interface ClassName ( CategoryName )

               // method declarations

               @end
ClassName+CategoryName.m

               #import "ClassName+CategoryName.h"



               @implementation ClassName ( CategoryName )

               // method definitions

               @end
main.m
               main()
               {
                 Toy * toy_object = [[Toy alloc] init];
                 [toy_object method1];
               }
•
               •
               •
Delegate
               •
               •
               •
               •
•   :


               •

               •
               •
               •

               •
•

               •   -(void)forwardInvocation:(NSInvocation *)anInvocation

               •   NSIvocation

               •   -(SEL)selector :                              .

               •   -(id)target :                             .

               •   -(void) invokeWithTarget:(id)anObject :
NSInvocation
               An NSInvocation is an Objective-C message rendered static, that is, it is an action
               turned into an object. NSInvocation objects are used to store and forward messages
               between objects and between applications, primarily by NSTimer objects and the
               distributed objects system.

               An NSInvocation object contains all the elements of an Objective-C message: a target, a
               selector, arguments, and the return value. Each of these elements can be set directly, and
               the return value is set automatically when the NSInvocation object is dispatched.

               An NSInvocation object can be repeatedly dispatched to different targets; its arguments
               can be modified between dispatch for varying results; even its selector can be changed to
               another with the same method signature (argument and return types). This flexibility
               makes NSInvocation useful for repeating messages with many arguments and
               variations; rather than retyping a slightly different expression for each message, you
               modify the NSInvocation object as needed each time before dispatching it to a new
               target.

               NSInvocation does not support invocations of methods with either variable numbers of
               arguments or union arguments. You should use the invocationWithMethodSignature:
               class method to create NSInvocation objects; you should not create these objects using
               alloc and init.

               This class does not retain the arguments for the contained invocation by default. If those
               objects might disappear between the time you create your instance of NSInvocation and
               the time you use it, you should explicitly retain the objects yourself or invoke the
               retainArguments method to have the invocation object retain them itself.

               Note: NSInvocation conforms to the NSCoding protocol, but only supports coding by an
               NSPortCoder. NSInvocation does not support archiving.
Tasks
               Creating NSInvocation Objects
                1    + invocationWithMethodSignature:
               Configuring an Invocation Object
                1    – setSelector:
                2    – selector
                3    – setTarget:
                4    – target
                5    – setArgument:atIndex:
                6    – getArgument:atIndex:
                7    – argumentsRetained
                8    – retainArguments
                9    – setReturnValue:
                10   – getReturnValue:
               Dispatching an Invocation
                1    – invoke
                2    – invokeWithTarget:
               Getting the Method Signature
                1    – methodSignature
Foundation
                   : mutable
                   : immutable




                                     NSArray              NSMutableArray

                                      NSData               NSMutableData

                                    NSDictionay         NSMutableDictionary

                                       NSSet                NSMutableSet

                                     NSString             NSMutableString

                                 NSAttributedString   NSMutableAttributedString

                                  NSCharaterSet        NSMutableCharacterSet

                                    NSIndexSet           NSMutableIndexSet
•                                           “”                @
                     .

               •   NSString *myname =@”jin seok song”;

               •   NSString *work = [@”Name: “ stringByAppendingString: myname];

               •   #define Manufacturer @”BrainLab, Inc.”

               •                                                    .

               •                                                                   .
NSString


               •
               •       Unicode   .
NSString method
               -
               +(id) stringWithFormat: (NSString *) format, ...;

                 )
               NSString *height;
               height = [NSString stringWithFormat: @”Your height is %d feet, %d inches”, 5, 11];

               -                  (                   )
               - (unsigned int) length;
                  )
               unsigned int length = [height length];
               NSLog(@”height’s length =%d”, length);

               -
               - (BOOL) isEqualToString: (NSString *) aString;

                  )
               NSString *thing1 = @”hello 5”;
               NSString *thing2;
               thing2 = [NSString stringWithFormat:@”hello %d”, 5];

               if([thing1 isEqualToString: thing2])
               {
                    NSLog(@”They are the same!”);
                    }
?

               - (BOOL) hasPrefix: (NSString *) aString;
               - (BOOL) hasSuffix: (NSString *) aString;

                   )
               NSString *filename = @”draft-chapter.pages”;
               if([filename hasPrefix:@”draft”])
               {
                     NSLog(@”It has draft word”);
               }



               NSMutableString class                                .
               MSMutableString
               + (id) stringWithCapacity: (unsigned) capacity;

                  )
               NSMutableString *string;
               string = [NSMutableString stringWithCapacity: 42];


               - (void) appendingString: (NSString *) aString;
               - (void) appendFormat: format,...;

                  )
               NSMutableString *string;
               string = [NSMutableString stringWithCapacity: 50];
               [string appendString: @”Hello there “];
               [string appendFormat: @”human %d!’, 39];
               NSLog(“@% “, string);
NSArray :
               NSDictionary :                     pair
               NSSet:

               NSArray
               - int, float, enum, struct
               - nil
                  )
               NSArray *array;
               array = [NSArray arrayWithObjects: @”one”, @”two”, @”three”, nil];

               - (unsigned) count;
               - (id) objectAtIndex: (unsigned int) index;

                  )
               int i;
               for (i = 0; i < [array count]; i++)
               {
                  NSLog(@”index %d has %@.”, i, [array objectAtIndex: i]);
               }
NSDictionary

               + (id) dictionaryWithObjectsAndKey: (id) firstObject, ...;

               Toy *t1 = [Toy new];
               Toy *t2 = [Toy new];
               Toy *t3 = [Toy new];
               Toy *t4 = [Toy new];

               NSDictionary *toyshop;

               toyshop = [NSDictionary dictionaryWithObjectsAndKeys:
               t1, @”bear”, t2, @”lego”, t3, @”tank”, t4, @”barbie”, nil];

               NSDictionary
               - (id) objectForKey: (id) aKey;
               Toy *toy = [toyshop objectForKey: @”lego”];
NSMutableDictionary
               +(id) dictionaryWithCapacity: (unsigned int)numItems;


               - (void) setObject : (id) anObject forKey : (id) aKey;



               - (void) removeObjectForKey: (id) aKey;

               [toyshop removeObjectForKey: @”barbie”];

오브젝트C(pdf)

  • 1.
    Object C Bit Academy
  • 3.
    Object C • C 80 Brad J. Cox • 1980 NextStep • Object C
  • 4.
    : ( , ) • :
  • 5.
    • 0 • . • Car *myCar = [[Car alloc] init];
  • 6.
    : alloc (call retain) • : release • Car *myCar = [[Car alloc] init]; • printf(“The retain count is %dn”, [myCar retainCount]); • [myCar release]; • printf(“Retain count is now %dn”, [myCar retainCount]); //error • , retain release
  • 7.
    , , • : • : • : • : initWithName: andModel: andYear: ( )
  • 8.
    • .
  • 9.
    .h • - • + • .m
  • 10.
    • .m ( ) #import “Car.h” @implementation Car -(id) init The init method defined in the NSObject class does no initialization, it simply returns self { self = [super init]; if(!self) = return nil; make = nil; model = nil; year = 1901; return self; }
  • 11.
    [obj method_name]; obj : method_name .
  • 12.
    + . +(NSString *) motto; • [ _ _ ] • • • •
  • 13.
    + (NSString *)motto { return (@”Ford Prefects are Mostly Harmless”); } [Car motto]; . [UIApplication sharedApplication]; [UIDevice currentDevice]; [[NSArray alloc] init]; [NSArray array]; -> .
  • 14.
    • C • -C factory, factory method • . • • NSObject class .
  • 15.
    alloc class
  • 16.
    + • •
  • 17.
    -C static • • ,
  • 18.
    for/in for loop NSArray *colors = [NSArray arrayWithObjects:@”Blacks”, @”Silver”, @”Gray”, nil]; for (NSString *color in colors) { printf(“Consider buying a %s car”, [color UTF8String]); }
  • 19.
    NSObject NSArray NSString UIResponder UIView UILabel UIControl UITextField UISlider object C . . .
  • 20.
    NSObject • -C ( , , , ) • NSObject .
  • 22.
    NSLog : C printf , stdout stderr . NSString • NSString @” ” . • NSLog • NSLog(@”Make %@”, make);
  • 23.
    Scope of InstanceVariables Directive Meaning @private The instance variable is accessible only within the class that declares it. @protected The instance variable is accessible within the class that declares it and within . classes that inherit it. All instance variables without an explicit scope directive have @protected @interface Worker : NSObject scope. { @public char *name; The instance variable is accessible everywhere. @private @package int age; Using the modern runtime, an @package instance variable has @public scope inside the executable image that implements the class, but acts like @private char *evaluation; outside. @protected The @package scope for Objective-C instance variables is analogous to private_extern for C variables and functions. id job; Any code outside the class implementation’s image that tries to use the instance variable gets a link error. float wage; This scope is most useful for instance variables in framework classes, where @public @private may be too restrictive but @protected or @public too permissive. id boss; } protected: name, job, wage private: age, evaluation public: boss
  • 24.
    • • @property(attributes) type name; • attributes : assign, retain, copy • retain, copy : release message sent to the previous value • attributes: readonly, readwrite( readwrite) • attribute : nonatomic (default is atomic)
  • 25.
    dot syntax • . = • . , . • property-synthesize . • retain, release
  • 26.
    retained property • property (retain) NSArray *colors; • @synthesize colors; • . • self.colors = [NSArray arrayWithObjects: @”Gray”, @”Silver”, @”Black”];
  • 27.
    retain count 1 1 0 dealloc . • .
  • 28.
    alloc init 1 . -(void) leakyMethod { NSArray *array = [[NSArray alloc] init]; } -(void) properMethod { NSArray *array = [[NSArray alloc] init]; [array release]; } -(void) anotherProperMethod { NSArray *array = [[[NSArray alloc] init] autorelease]; } -(void) yetAnotherProperMethod { NSArray *array = [NSArray array]; // . }
  • 29.
    release • Car *car = [[[Car alloc] init] autorelease] • Car *car = [Car car]; • + (Car *) car { class method, convenience method return [[[Car alloc] init] autorelease]; }
  • 30.
    • • 1 .
  • 31.
    • property retain • @property (retain) NSArray *colors •
  • 32.
    Retain Count When you create an object, it has a retain count of 1. • When you send an object a retain message, its retain count is incremented by 1. • When you send an object a release message, its retain count is decremented by 1. • When you send an object a autorelease message, its retain count is decremented by 1 at some stage in the future.
  • 33.
    Autorelease • release release • release pool autorelease release pool release •
  • 34.
    • • . • • To declare methods that others are expected to implement • To declare the interface to an object while concealing its class • To capture similarities among classes that are not hierarchically related
  • 35.
    protocol protocol_A.h #import <Foundation/Foundation.h> @protocol Protocol_A - methodA; @required - methodB; @optional - methodC; @end
  • 36.
    Toy.h #import “protocol_A.h” @interface Toy:NSObject <protocol_A> { NSString * name; } @end
  • 37.
    Toy.m #import “protocol_A.h” @implementation Toy - method_A { printf(“method_A implemented in Toyn”); } - method_B { printf(“method_B implemented in Toyn”); } @end
  • 38.
    main.m #import <Foundation/Foundation.h> #import “Toy.h” main() { Toy *toy_object = [[Toy alloc] init]; [toy_object method_A]; [toy_object method_B]; [toy_object release]; }
  • 39.
    • . • . • (.h) (.m) . • + .h + .m • + .m .
  • 40.
    , • Subclass • . . - , - - - . - .
  • 41.
    ClassName+CategoryName.h #import "ClassName.h" @interface ClassName ( CategoryName ) // method declarations @end
  • 42.
    ClassName+CategoryName.m #import "ClassName+CategoryName.h" @implementation ClassName ( CategoryName ) // method definitions @end
  • 43.
    main.m main() { Toy * toy_object = [[Toy alloc] init]; [toy_object method1]; }
  • 44.
    • •
  • 45.
    Delegate • • • •
  • 46.
    : • • • • •
  • 47.
    • -(void)forwardInvocation:(NSInvocation *)anInvocation • NSIvocation • -(SEL)selector : . • -(id)target : . • -(void) invokeWithTarget:(id)anObject :
  • 48.
    NSInvocation An NSInvocation is an Objective-C message rendered static, that is, it is an action turned into an object. NSInvocation objects are used to store and forward messages between objects and between applications, primarily by NSTimer objects and the distributed objects system. An NSInvocation object contains all the elements of an Objective-C message: a target, a selector, arguments, and the return value. Each of these elements can be set directly, and the return value is set automatically when the NSInvocation object is dispatched. An NSInvocation object can be repeatedly dispatched to different targets; its arguments can be modified between dispatch for varying results; even its selector can be changed to another with the same method signature (argument and return types). This flexibility makes NSInvocation useful for repeating messages with many arguments and variations; rather than retyping a slightly different expression for each message, you modify the NSInvocation object as needed each time before dispatching it to a new target. NSInvocation does not support invocations of methods with either variable numbers of arguments or union arguments. You should use the invocationWithMethodSignature: class method to create NSInvocation objects; you should not create these objects using alloc and init. This class does not retain the arguments for the contained invocation by default. If those objects might disappear between the time you create your instance of NSInvocation and the time you use it, you should explicitly retain the objects yourself or invoke the retainArguments method to have the invocation object retain them itself. Note: NSInvocation conforms to the NSCoding protocol, but only supports coding by an NSPortCoder. NSInvocation does not support archiving.
  • 49.
    Tasks Creating NSInvocation Objects 1 + invocationWithMethodSignature: Configuring an Invocation Object 1 – setSelector: 2 – selector 3 – setTarget: 4 – target 5 – setArgument:atIndex: 6 – getArgument:atIndex: 7 – argumentsRetained 8 – retainArguments 9 – setReturnValue: 10 – getReturnValue: Dispatching an Invocation 1 – invoke 2 – invokeWithTarget: Getting the Method Signature 1 – methodSignature
  • 50.
    Foundation : mutable : immutable NSArray NSMutableArray NSData NSMutableData NSDictionay NSMutableDictionary NSSet NSMutableSet NSString NSMutableString NSAttributedString NSMutableAttributedString NSCharaterSet NSMutableCharacterSet NSIndexSet NSMutableIndexSet
  • 51.
    “” @ . • NSString *myname =@”jin seok song”; • NSString *work = [@”Name: “ stringByAppendingString: myname]; • #define Manufacturer @”BrainLab, Inc.” • . • .
  • 52.
    NSString • • Unicode .
  • 53.
    NSString method - +(id) stringWithFormat: (NSString *) format, ...; ) NSString *height; height = [NSString stringWithFormat: @”Your height is %d feet, %d inches”, 5, 11]; - ( ) - (unsigned int) length; ) unsigned int length = [height length]; NSLog(@”height’s length =%d”, length); - - (BOOL) isEqualToString: (NSString *) aString; ) NSString *thing1 = @”hello 5”; NSString *thing2; thing2 = [NSString stringWithFormat:@”hello %d”, 5]; if([thing1 isEqualToString: thing2]) { NSLog(@”They are the same!”); }
  • 54.
    ? - (BOOL) hasPrefix: (NSString *) aString; - (BOOL) hasSuffix: (NSString *) aString; ) NSString *filename = @”draft-chapter.pages”; if([filename hasPrefix:@”draft”]) { NSLog(@”It has draft word”); } NSMutableString class . MSMutableString + (id) stringWithCapacity: (unsigned) capacity; ) NSMutableString *string; string = [NSMutableString stringWithCapacity: 42]; - (void) appendingString: (NSString *) aString; - (void) appendFormat: format,...; ) NSMutableString *string; string = [NSMutableString stringWithCapacity: 50]; [string appendString: @”Hello there “]; [string appendFormat: @”human %d!’, 39]; NSLog(“@% “, string);
  • 55.
    NSArray : NSDictionary : pair NSSet: NSArray - int, float, enum, struct - nil ) NSArray *array; array = [NSArray arrayWithObjects: @”one”, @”two”, @”three”, nil]; - (unsigned) count; - (id) objectAtIndex: (unsigned int) index; ) int i; for (i = 0; i < [array count]; i++) { NSLog(@”index %d has %@.”, i, [array objectAtIndex: i]); }
  • 56.
    NSDictionary + (id) dictionaryWithObjectsAndKey: (id) firstObject, ...; Toy *t1 = [Toy new]; Toy *t2 = [Toy new]; Toy *t3 = [Toy new]; Toy *t4 = [Toy new]; NSDictionary *toyshop; toyshop = [NSDictionary dictionaryWithObjectsAndKeys: t1, @”bear”, t2, @”lego”, t3, @”tank”, t4, @”barbie”, nil]; NSDictionary - (id) objectForKey: (id) aKey; Toy *toy = [toyshop objectForKey: @”lego”];
  • 57.
    NSMutableDictionary +(id) dictionaryWithCapacity: (unsigned int)numItems; - (void) setObject : (id) anObject forKey : (id) aKey; - (void) removeObjectForKey: (id) aKey; [toyshop removeObjectForKey: @”barbie”];