我在命令行应用程序中创建了两个类(FirstClass和SecondClass)。我在FirstClass方法中创建了一个SecondClass对象。现在我想在main中调用该方法并释放分配给该对象的内存。我的代码如下..
@implementation FirstClass
+(NSMutableArray *) addObject{
NSMutableArray *namesArray = [[[NSMutableArray alloc]init] autorelease];
SecondClass *second = [[SecondClass alloc]init];
NSLog(@"Before adding object, count = %ld ",[second retainCount]); //RC = 1
[second setName:@"Mobicule"];
[namesArray addObject:second];
NSLog(@"First object addeded, count = %ld ",[second retainCount]); //RC = 2
[second release];
NSLog(@"After release, count = %ld",[second retainCount]); //RC = 1
return namesArray;
}
@end
我想将保留计数设为零..
主要功能如下..
int main (int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
// NSLog(@"Hello, World!");
NSMutableArray *arrayMain = [[NSMutableArray alloc]init];
arrayMain = [FirstClass addObject];
for (int i = 0; i<[arrayMain count]; i++) {
NSLog(@"%@",[[arrayMain objectAtIndex:i] name]);
}
NSLog(@"%ld",[arrayMain retainCount]);
}
return 0;
}
答案 0 :(得分:0)
我假设你的名字的合成属性是retain
。
+(NSMutableArray *) addObject{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *namesArray = [[NSMutableArray alloc]init];
SecondClass *second = [[[SecondClass alloc]init]autorelease];
NSLog(@"Before adding object, count = %ld ",[second retainCount]); //RC = 1
[second setName:@"Mobicule"]; //implementation will handle the release for you
[namesArray addObject:second];
NSLog(@"First object addeded, count = %ld ",[second retainCount]); //RC = 2
[pool release];
NSLog(@"After pool release, count = %ld",[second retainCount]); //RC=1
return [namesArray autorelease];
}
你永远不应该使用-retainCount,因为它从不告诉你任何事情 是有用的。