cableload
cableload

Reputation: 4385

Memory allocation in objective-c

I am trying to follow this tutorial as i am new to objective C. I am trying to understand this initialization code

#import "RWTScaryBugDoc.h"
#import "RWTScaryBugData.h"
@implementation RWTScaryBugDoc
@synthesize data = _data;
@synthesize thumbImage = _thumbImage;
@synthesize fullImage = _fullImage;

- (id)initWithTitle:(NSString*)title rating:(float)rating thumbImage:(UIImage *)thumbImage fullImage:(UIImage *)fullImage {  
  if ((self = [super init])) {
  self.data = [[RWTScaryBugData alloc] initWithTitle:title rating:rating];
  self.thumbImage = thumbImage;
  self.fullImage = fullImage;
 }
return self;
}

@end

Here the class RWTScaryBugDoc contains three properties:data,thumbImage and fullImage. All are pointer objects. However on the initialization code memory is allocated only to the RWTScaryBugData and not to thumbImage and fullImage. why is that ? How would caller know to allocate a memory for thumbImage and fullImage ?

Upvotes: 0

Views: 55

Answers (3)

Rob
Rob

Reputation: 1034

The constructor there has 4 parameters. Title, rating, thumb and full. The first two are used for the data property. The user should assume that they need to pass in all parameters already allocated/initialized.

Think about this, if you had a second constructor that took in data, thumb and full, you would need to alloc/init data yourself and then pass it in.

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49920

There is no RWTScaryBugData to assign directly; one has to be made using the title and rating parameters. But there are parameters that can be (and are) directly assigned for thumbImage & fullImage.

The caller had to allocate space for all of the parameters passed; if she hadn't, she couldn't pass them.

Upvotes: 1

Jon Shier
Jon Shier

Reputation: 12800

The code you've posted merely assigns the existing UIImage objects to the properties, so no allocation is necessary. The images are likely allocated before you call the initializer.

Also, FYI, explicit @synthesize statements are unnecessary in modern Objective-C unless you're overriding the accessors.

Upvotes: 0

Related Questions