Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objectiveC autorelease issue, what is wrong with code?

Tags:

objective-c

New to 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"]);

}

I did not get compile time error, but run time error i got :

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 

Looks like it is something to do with memory issue. some one point out the issue ?

NOTE: With all your inputs, i could resolve the autorelease issue, but still

NSLog (@" KVC Retrieveal  %i ", [t valueForKey:@"x"]);

does not print the proper value but the garbage. Am i doing something wrong?

like image 272
Whoami Avatar asked Dec 12 '22 03:12

Whoami


1 Answers

When you are in the run loop of an application, there is a default autorelease pool created for you. However, when you are running with your own main, you need to create an autorelease pool manually at the top of your main, and drain it periodically.

NSAutoreleasePool *myPool = [[NSAutoreleasePool alloc] init];
// Your code that uses autorelease...
[myPool drain];

If you are compiling with the new LLVM compiler, use the new @autoreleasepool feature instead.

like image 133
Sergey Kalinichenko Avatar answered Jan 11 '23 19:01

Sergey Kalinichenko