objectiveC autorelease问题,代码有什么问题?

Who*_*ami 3 objective-c

Objective-C的新手,

#import <objc/objc.h>
#import <Foundation/Foundation.h>

@interface Test:NSObject
{
  int x,y, abc;
  NSString *v1, *v2;
}
@property int x , y, abc;
-(void) print;

@end

@implementation Test
@synthesize x,y, abc;
-(void) print
{
 NSLog (@"v1 and v2 values %i, %i ", v1, v2);
}

@end

int main ( int argc, char **argv)

{
  Test *t = [[Test alloc] init];
  /* Synthesized Set Method */
  [t setX:100];
  [t setY:200];
 /* Synthesized Get Method */
  NSLog (@"Retrieving Values %i, %i ",[t x], [t y]);

 /* another Way to retrieve the throuhg KVC Model */
 NSLog (@" KVC Retrieveal  %i ", [t valueForKey:@"x"]);
Run Code Online (Sandbox Code Playgroud)

}

我没有得到编译时错误,但我得到了运行时错误:

2012-04-11 16:25:08.470 testpgm[22237] Retrieving Values 100, 200 
2012-04-11 16:25:08.513 testpgm[22237] autorelease called without pool for object (0x8e78ca0) of class NSMethodSignature in thread <NSThread: 0x8e23a08>
2012-04-11 16:25:08.514 testpgm[22237] autorelease called without pool for object (0x8e94610) of class NSIntNumber in thread <NSThread: 0x8e23a08>
2012-04-11 16:25:08.514 testpgm[22237]  KVC Retrieveal  149505552 
Run Code Online (Sandbox Code Playgroud)

看起来它与内存问题有关.有人指出这个问题?

注意:使用所有输入,我可以解决自动释放问题,但仍然

NSLog (@" KVC Retrieveal  %i ", [t valueForKey:@"x"]);
Run Code Online (Sandbox Code Playgroud)

没有打印正确的值,但垃圾.难道我做错了什么?

zap*_*aph 5

主例程不会创建自动释放池.

根据您使用的版本和编译器,使用这些方法之一.

更新或使用ARC:

int main(int argc, char *argv[])
{
    @autoreleasepool {

    // your code

    }
}
Run Code Online (Sandbox Code Playgroud)

要么

int main(int argc, char *argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

     // your code

    [pool drain];
}
Run Code Online (Sandbox Code Playgroud)

该代码还有许多其他问题,例如:

NSLog (@"v1 and v2 values %i, %i ", v1, v2);
Run Code Online (Sandbox Code Playgroud)

应该是

NSLog (@"v1 and v2 values %@, %@ ", v1, v2);
Run Code Online (Sandbox Code Playgroud)

%@用于打印对象,%i用于整数.

这条线:

NSLog (@" KVC Retrieveal  %i ", [t valueForKey:@"x"]);
Run Code Online (Sandbox Code Playgroud)

很有趣因为valueForKey返回一个对象(在本例中是一个NSNumber)所以正确的语句是:

NSLog (@" KVC Retrieveal  %@ ", [t valueForKey:@"x"]);
Run Code Online (Sandbox Code Playgroud)

使用这些更正运行程序会产生:

Retrieving Values 100, 200 
KVC Retrieveal  100 
Run Code Online (Sandbox Code Playgroud)


das*_*ght 5

当您处于应用程序的运行循环中时,会为您创建一个默认的自动释放池.但是,当您使用自己的运行时main,需要在您的顶部手动创建自动释放池main,并定期将其耗尽.

NSAutoreleasePool *myPool = [[NSAutoreleasePool alloc] init];
// Your code that uses autorelease...
[myPool drain];
Run Code Online (Sandbox Code Playgroud)

如果要使用新的LLVM编译器进行编译,请改用新@autoreleasepool功能.