Bknee
Bknee

Reputation: 25

Strange behavior with NSString instance variable

Here is part of a class definition in an iOS program using reference counting (ARC):

@interface CapViewController : UIViewController 
{
    NSString *bottomBn;
    NSString *topBn;
}

@property (nonatomic, strong) NSString *bottomBn;
@property (nonatomic, strong) NSString *topBn;

@end

In the implementation I synthesize them:

@implementation CapViewController

@synthesize bottomBn;
@synthesize topBn;

The problem is when I try to assign values. If I step through the following lines in a class method (first time each instance variable is being used):

bottomBn = [NSString stringWithString:@"bottomBn"];        
topBn = [NSString stringWithString:@"topBn"];

After the first line has executed, the value of topBn becomes @"bottomBn" and bottomBn is nil The second line has no impact.

If I change the order the instance variables are defined in the class, i.e.:

NSString *topBn;
NSString *bottomBn;

then the first assignment has no effect and the second assignment results in "topBn" being assigned to bottomBn.

Using local variables it works as expected:

NSString *localbottomBn = [NSString stringWithString:@"defaultbottombutton"];        
NSString *localtopBn = [NSString stringWithString:@"defaulttopbutton"];

This seems bizarre behavior to me. I'd appreciate any help.

Upvotes: 2

Views: 280

Answers (2)

Lloyd18
Lloyd18

Reputation: 1682

I have same problems with other types and objects (even CGFloat and CGPoint). I think the problem is in debugger. Try to print you strings instead of look variables via debugger. For me NSLog function print what I expected.

I have no ideas why debugger have this unpredictable behavior (may be it's a bug), but now I prefere "NSLog debugging". It is sad.

Upvotes: 0

LuisEspinoza
LuisEspinoza

Reputation: 8538

You are not setting the autoreleased strings, you should set the strings as:

self.bottomBn = [NSString stringWithString:@"bottomBn"];        
self.topBn = [NSString stringWithString:@"topBn"];

Upvotes: 7

Related Questions