Could some one tell me why my array is out of scope? Here's my class:
// Paper.h
@interface Paper : NSObject {
NSMutableArray* items;
}
@property (retain) NSMutableArray* items;
// Paper.m
#import "Paper.h"
@implementation Paper {
@synthesize items;
}
// ParserUtil.m
@implementation ParserUtil {
+(Paper*) parsePaper:(NSString*)file {
...
Paper* paper = [[[Paper alloc] init] autorelease];
// does the following line is the best practice?
paper.items = [[[MutableArray alloc] init] autorelease];
Item* item = ...开发者_如何转开发; // create item instance
[paper.items addObject:item];
return paper;
}
// call the parser method
...
Paper* paper = [[ParserUtil parsePaper:@"SomeFile"] retain];
// when run to this line, the paper.items is out of scope
// seems all the items in the array are dispear
NSMutableArray* items = paper.items;
...
Could someone point out what is wrong here? Many thanks!
It isn't.
An object cannot be out of scope, because objects do not have scope. What they can be is unreachable, which is what happens when you don't have any variables holding the object's pointer.
Variables can be out of scope. You can only use a variable within the same scope in which you declared it; you can't begin a compound statement, declare a variable, finish the compound statement, and use the variable, and you can't declare a variable in one function or method and then use it in a different one.
You said in your other question that it's the debugger telling you the variable is out of scope. This means one of two three things:
- The variable really is out of scope. Move the variable or move the code that uses it, or just interrupt the debugger earlier (with a breakpoint, if necessary).
- The debugger is just being stupid. This happens a lot. Try the
po
command or sprinkle your code withNSLog
statements instead. - You're trying to examine a property-access expression. A property-access expression, by definition, must send an accessor message, which may have side effects; for that reason, the debugger won't do that just for you hovering over the expression, because that's too easy to do by accident. You must use the
po
command in the Debugger Console to send the accessor message and print the description of the result.
精彩评论