0
votes

Suppose I have a function

- (NSString *)fullNameCopy {
    return [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName];
}

Can somebody tell me how to call this function, how to assign its value to a new object, and how then to release it, avoiding memory leaks, and bad access.

Would it be like

NSSting *abc = [object fullNameCopy];

// Use it and release

[abc release];

or I should alloc abc string too ?

Update:

The point here, Can I return non-autorelease objects from a function and then release them in the calling function. As per Obj-C function naming conventions, a function name containing alloc or copy should return object assuming that calling function has the ownership.

As in above case, my function "fullNameCopy" return a non-autoreleased abject, and I want to release them in the calling function.

4

4 Answers

2
votes

You are right. Since the method name contains the word ‘copy’, Cocoa convention dictates that the method returns an object that is owned by the caller. Since the caller owns that object, it is responsible for releasing it. For example:

- (void)someMethod {
    NSString *abc = [object fullNameCopy];

    // do something with abc

    [abc release];
}

Alternatively, you could use -autorelease instead of -release:

- (void)someMethod {
    NSString *abc = [[object fullNameCopy] autorelease];

    // do something with abc
}
0
votes

Refer this post

UPDATE:

- (NSString *)fullNameCopy {
    NSString *returnString  = [NSString stringWithFormat:@"%@ %@", self.firstName, self.LastName]; // Autorelease object.
    return returnString;
}

-(void) someFunction {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSString *fullName = [self fullNameCopy];

    [pool release]
}
0
votes

Like This:

- (NSString *)fullName {

    NSString * retVal = [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName];

    return [retVal autoRelease];
}

Then

NSSting *abc = [object fullName];

-1
votes

return [[[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName]autorelease];