Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • alloc and init methods in objc

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 233
    Comment on it

    In Objective C we create objects wherever we want. NSObject class is the root class which holds alloc and init methods. Here is an example to understand the concept in details.

    id Object = [NSObject new];  // Creates and returns an initialized object
    
    id anotherObj = [NSObject alloc];   // Not yet ready for use...
    anotherObj = [anotherObj init];     // ...now it is.
    
    // good style: combine alloc and init:
    id MoreObj = [[NSObject alloc] init];  // identical to using new
    
    

    An initializer is a method that initializes an object. If the initialization does not require any parameters, the method to define is called init (i.e., you should override the base class initializer). This makes it possible to create instances of your class by using the new class method derived from NSObject:

    MyClass* myObj = [[MyClass alloc] init];   // allocate and initialize the object
    

    The above code creates a new instance of MyClass. To override the initializer for your class, optionally define it in the interface file:

    /* In MyObject.h, in the method declarations part */
    - (id) init;
    

    and implement it in the .m file:

    /* In MyObject.m */
    @implementation MyObject
    - (id) init
    {
        /* first initialize the base class */
        self = [super init]; 
        /* then initialize the instance variables */
        myMember = [AnotherClass new];
        /* finally return the object */
        return self;
    }
    @end
    

    If the initialization requires additional parameters, you should define an initializer like initWithParam:, for example

    - (id) initWithMember: (AnotherClass) member
    {
        self = [super init];
        myMember = [[AnotherClass alloc] initWithValue: member];
        return self;
    }
    Even then, it is often advisable to define a "default" initializer that calls your initWithXXX method with suitable default parameters:
    
    - (id) init
    {
        return [self initWithMember: someDefaultValue];
    }
    

    A deallocator is a method that is responsible to release all resources an object holds. In ARC we need not to implement this:-

    - (void) dealloc
    {
       [myMember release];
       [super dealloc];
    }
    
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: