开发者

NSString alloc/init generates 'Redefinition of myStr' error....?

I seem to be generating a lot of questions with this one little iPhone app....

I am attempting to stuff an NSMutableArray with NSStrings, and I am working like this:

...
NSString *myStr = [[NSString alloc] initWithString:@"Jupiter II"]; 
[txtArray addObject: myStr];
[m开发者_如何转开发yStr release];

NSString *myStr = [[NSString alloc] initWithString:@"Could this be OUR Waffles?"];
// in this second block, the line above generates the error: 'Redefinition of myStr'. Why?
[txtArray addObject: myStr];
[myStr release];
...

The first block generates no errors, but the subsequent blocks (identical save for the content of each string object) all generate the error, 'Redefinition of myStr'. Why?

I know that this is going to be a facepalm, but I just gotta know, and get beyond this!

hanks for any and all assistance!

Kind regards,

Steve O'Sullivan


Just remove NSString* from the second block:

NSString *myStr = [[NSString alloc] initWithString:@"Jupiter II"]; 
[txtArray addObject: myStr];
[myStr release];

myStr = [[NSString alloc] ...

Each time you write something like NSString *myStr you declare new variable - and variable names must be different in the same scope. But you can reuse the same variable to store different objects - as you do in the code above


Maybe it was just for the sake of example, but your first three lines of code can be substituted with:

[txtArray addObject:@"Jupiter II"]

Also, creating an array of strings is as simple as:

[NSArray arrayWithObjects:@"Jupiter II",
                          @"Could this be OUR Waffles",
                          nil];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜