Advertise Mobile SDKs Books Events Forum News Social Networking Support Us
Follow @iphonedevsdk on Twitter

Interface 2, Advanced iOS
Mockup & Code Gen
($9.99)

Make your own iPhone apps
and run them live!
(free)

Pic Frame Dynamo: Photo Editing
($0.99)

Abiliator
($1.99)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum

View Single Post
Old 03-19-2010, 03:03 AM   #1 (permalink)
SteveMobs
Registered Member
 
Join Date: Dec 2009
Posts: 98
SteveMobs is on a distinguished road
Question Memory Management in Custom Class

Hello,

by doing more and more Objective-C I somehow get more and more confused about memory management. I have read the according document but what I need are some best practice examples. Here I have a small example class and a couple of questions.

Are there any other helpful guides / documents explaining how to write custom classes?
Code:
@interface MyClass : NSObject {
	NSString *name;
	CoolObject *coolObject;
}

@property (readonly, retain) NSString *name;
@property (readwrite, retain) CoolObject *coolObject;

- (id)initWithName:(NSString *)theName;
- (void)doWhatever;

@end
@implementation MyClass

@synthesize name, coolObject;

// custom initializer
- (id)initWithName:(NSString *)theName {
	if (self = [super init]) {
		name = theName;
		coolObject = [[CoolObject alloc] init];
	}
	return self;
}

// overwrite setter
- (void)setName:(NSString *)theName {
	if (theName != nil && [theName length] > 0) {
		name = theName;
	}
}

// overwrite setter
- (void)setCoolObject:(CoolObject *)theObject {
	if (theObject != nil) {
		coolObject = theObject;
	}
}

- (void)doWhatever {
    self.coolObject = [[CoolObject alloc] init];
}

- (void)dealloc {
	[name release];
	[coolObject release];
	[super dealloc];
}
@end
1. should a NSString property be assigned, retained or copied? What are best practices? Or when should I chose which?

2. in the custom initializer:
Is there a leak assigning the object?
Would this be better?

CoolObject *tmp = [[CoolObject alloc] init];
coolObject = tmp;
[tmp release];

What about the method doWhatever? Does this leak an object?
should it rather be:

[coolObject release];
CoolObject *tmp = [[CoolObject alloc] init];
self.coolObject = tmp;
[tmp release];

3. overwritten setters: is there a call of [name release] / [coolObject release] missing before the assignment?

4. dealloc: is it correct that

coolObject = nil;

is similiar to

[coolObject release];
coolObject = nil;

Thanks!
SteveMobs is offline   Reply With Quote
 

» Advertisements
» Stats
Members: 175,545
Threads: 94,069
Posts: 402,688
Top Poster: BrianSlick (7,989)
Welcome to our newest member, ceolacc18
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 02:25 PM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.