Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Confused on when to alloc and init an instance in Objective C. Any Advice?

My guess is when you create an instance of a custom class.

2 Answers

It depends on what you are doing, and the specifics of the object class that you are working with -- you'll need to consult implementation/documentation.

Here is a very simple example (and one possibility):

/// Sample.h

@interface Sample : NSObject

@property (strong, nonatomic) NSString *myString;

- (NSString *)instanceMethod;
+ (NSString *)classMethod;

@end

/// Sample.m

@implementation Sample

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.myString = @"I am an instance variable!";
    }
    return self;
}

- (NSString *)instanceMethod {
    return self.myString;
}

+ (NSString *)classMethod {
    return @"You called the class method!";
}

@end

In order for you to call instanceMethod, you must allocate (alloc) memory and initialize (init) your object:

Sample *sampleInstance = [[Sample alloc] init];

NSString *someString = [sample instanceMethod];

NSLog(@"%@", someString);
// Prints => "I am an instance variable!"

However, it is not necessary to call alloc or init if you want to use the classMethod:

NSString *anotherString = [Sample classMethod];

NSLog(@"%@", anotherString);
// Prints => "You called the class method!'

I hope this helps, and here are a few links for further reading:

Object Initialization

Define Classes

Yes it helps a lot! Thanks man!