On Tue, Aug 17, 2010 at 4:03 PM, James Miller <jmiller3...@gmail.com> wrote:

> Hello.
>
> I'm a little new to Objective-C / Cocoa so please don't shoot me, but I've
> been looking around for a few hours and can't seem to figure out what I'm
> doing wrong on my own and could use a second/third/fourth set of eyes.
>
> I have NSTimer that runs several times a second against an NSString called
> level,  which is 190 characters long and previously initialized from:
>
> // NSString *level = [[NSString alloc]
> //
> initWithContentsOfFile:path
> //
> encoding:NSUTF8StringEncoding
> //                                               error:&error];
>
>
> During the timer call, the level NSString is modified by the following line
> of code:
>
> level=[level stringByReplacingCharactersInRange:NSMakeRange(5,1)
> withString:@" "];
>
> This operation appears to succeed as I print it via NSLog and it looks fine
> and the length checks out, but the next time through the NSTimer I get a bus
> error and the application dies.
>
> If I comment out the line above, the code continues to run fine. Am I doing
> something wrong in terms of how I am using this method or assigning it back
> to the NSString?
>
>
>
The result of the stringByReplacingCharactersInRange: method call is not
retained between NSTimer callback invocations.

It will leak memory, but as a quick test of that diagnosis, replace this
line:
  level=[level stringByReplacingCharactersInRange:NSMakeRange(5,1)
withString:@" "]
with
level=[[level stringByReplacingCharactersInRange:NSMakeRange(5,1)
withString:@" "] retain];

If that works, as a permanent fix declare the variable "level" a property of
the class and use synthesized accessors to assign the value of  "level",
which will retain/release it correctly:


#1:
add to your header file:
@property(readwrite, retain) NSString *level;

#2:
you should already have the variable defined in your header:
NSString *level;

#3:
Add to your .m file
@synthesize level;

#4:
and replace your stringByReplacingCharactersInRange invocation line with
this:
self.level=[self.level stringByReplacingCharactersInRange:NSMakeRange(5,1)
withString:@" "];

or if you prefer this style
[self setLevel:[ [self level]
stringByReplacingCharactersInRange:NSMakeRange(5,1) withString:@" "]];


- Allen
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to