我想知道如何在全班中访问NSString。说我有这些代码:
- (void) init {
NSArray *elements = [xpathParser search:@"//foo"];
TFHppleElement *element = [elements objectAtIndex:0];
NSString *data = [element content];
NSArray *elements1 = [xpathParser search:@"//foo2"];
TFHppleElement *element2 = [elements1 objectAtIndex:0];
NSString *data2 = [element2 content];
}
我想使用数据&全班的data2,我该怎么做?
我想在这里显示结果:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
switch (indexPath.row) {
case 0 :
cell.textLabel.text = (@"%@", data);
break;
case 1:
cell.textLabel.text = (@"%@", data2);
break;
}
// Email & Password Section
return cell;
}
答案 0 :(得分:1)
通过在方法之外声明它们来使它们成为类中的变量,例如:
NSString *data;
NSString *data2;
- (void) init {
NSArray *elements = [xpathParser search:@"//foo"];
TFHppleElement *element = [elements objectAtIndex:0];
data = [[element content] retain];
NSArray *elements1 = [xpathParser search:@"//foo2"];
TFHppleElement *element2 = [elements1 objectAtIndex:0];
data2 = [[element2 content] retain];
}
以后:
- (void)dealloc {
[data release];
[data2 release];
}
答案 1 :(得分:1)
为什么不让它们properties
并使用生成的setter?
所以在.h
文件中:
@interface YourClass {
}
@property (nonatomic, copy) NSString *data;
@property (nonatomic, copy) NSString *data2;
在.m
文件中:
@synthesize data, data2;
- (void) init {
NSArray *elements = [xpathParser search:@"//foo"];
TFHppleElement *element = [elements objectAtIndex:0];
[self setData:[element content]];
NSArray *elements1 = [xpathParser search:@"//foo2"];
TFHppleElement *element2 = [elements1 objectAtIndex:0];
[self setData2:[element2 content]];
}