I am trying out a program in Xcode, and I have created a new Mac Cocoa Application. I have a class called Photo with two instance variables Caption, Photographer. In the main function, I supply values to them as follows.
Photo *obj = [[Photo alloc]init];
obj.caption=@"Something";
obj.photographer=@"Hari";
NSLog(@"Name: '%@'",[obj caption]);
[obj release];
I 开发者_如何学JAVAget the output called Name: 'Something', but along with that I get this line
2011-02-22 11:56:03 test_1[1402:a0f] * __NSAutoreleaseNoPool(): Object 0x100002078 of class NSCFString autoreleased with no pool in place - just leaking
Can someone please explain why this line is appearing in the console?
Thanks,
Hariharan
Cocoa makes use of autorelease pools. An autorelease pool keeps references to objects that have been autoreleased and, when the pool is drained, it sends a -release
message to those autoreleased objects.
In the vast majority of cases, Cocoa applications should have at least one autorelease pool in place because Cocoa makes heavy use of autoreleased objects. When a Cocoa application is run, Cocoa automatically creates autorelease pools for the application.
In your case, it seems that your application is a Foundation program instead of a full blown Cocoa application. As such, it is your responsibility to set up an autorelease pool for your program. For instance,
int main() {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Photo *obj = [[Photo alloc] init];
// …
[pool drain];
return 0;
}
Note that the autorelease pool is not strictly necessary. If there’s no autorelease pool, your program will output that warning and, depending on the specifics of your program, you might leak objects. As leaking memory is a bad feature in a program, especially in long-lived programs or programs that allocate a lot of memory, it is advisable to always set up an autorelease pool.
That said, you haven’t sent -autorelease
yourself in that piece of code, so why is there an autoreleased string? I’m assuming you’ve synthesised the caption
property, and the compiler has created an accessor method that returns an autoreleased string containing the photo caption. When you send [obj caption]
, you get an autoreleased string, and consequently a warning since you haven’t set up an autorelease pool.
精彩评论