2013-04-18 96 views
1

我在我的程序中創建堆棧類,我希望存儲NSString值。 這是Stack類:如何在堆棧中存儲NSString

@interface Stack : NSObject 
- (void)push:(id)obj; 
- (id)pop; 
- (BOOL)isEmpty; 
@end 
@implementation Stack 
{ 
    NSMutableArray *stack; 
} 
- (id)init 
{ 
    self = [super init]; 
    if(self!= nil){ 
     stack = [[NSMutableArray alloc] init]; 
    } 
    return self; 
} 
- (void)push:(id)obj 
{ 
    [stack addObject:obj]; 
} 
- (id)pop 
{ 
    id lastobj = [stack lastObject]; 
    [stack removeLastObject]; 
    return lastobj; 
} 
- (BOOL)isEmpty 
{ 
    return stack.count == 0; 
} 
@end 

我也有另外一個類名:TableViewController 我想,當點擊在TableViewController店細胞的ID從URL

接收小區,這是我的代碼:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 

{ 
    // I want that xCode value with xCode2 value push in stack 

    NSLog(@"Row in Tab : %d",indexPath.row); 

    if ([Folder containsObject:[All objectAtIndex:indexPath.row]]) { 
     NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.%d/mamal/filemanager.php?dir=%@&folder=%d&id",IP,xCode,indexPath.row]]; 
     NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
     NSURLResponse *response = nil; 
     NSError *err = nil; 
     NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err]; 
     NSString *responseString = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding]; 
     xCode2 = responseString;   //this is new cell's id.I want to push this value in stack 
     NSLog(@"xcode : %@", xCode2); 

     [self performSegueWithIdentifier:@"segue4" sender:self]; 
    } 

    else 
    { 
     [self performSegueWithIdentifier:@"segue3" sender:self]; 

    } 
} 

最上面的代碼我想點擊單元格中的單元格推入堆棧中的兩個值(xCode & xCode2)但我不知道要使用堆棧。

+0

您是否在使用ARC? – dreamlax

+0

你在哪裏實現了'addObject:'etc?我想你想從'NSMutableArray'而不是'NSObject'繼承。然後從'init'方法中刪除'stack = ...'語句。 –

+0

是我使用ARC – janatan

回答

1
  1. 你需要保存您的堆棧變量..我會做它的成員VAR:

    @implementation TableViewController { 
        Stack *_stack; 
    } 
    ... 
    
  2. 然後單擊單元格時,按下值

    ... 
    if(!_stack) 
        _stack = [[Stack alloc] init]; 
    [_stack push:xcode2]; 
    ... 
    
+0

我的朋友如何彈出對象在堆棧 – janatan

+0

這回答了這個問題,但可能不是你想要的...實際上我沒有得到你想要的,但是這本身並沒有用 –

+0

調用[_stack pop];) –

0

除了Daij-Djan提出的建議,請執行以下操作:

@interface Stack : NSMutableArray 
- (void)push:(id)obj; 
- (id)pop; 
- (BOOL)isEmpty; 
@end 
@implementation Stack 

- (id)init 
{ 
    self = [super init]; 
    if(self!= nil){ 
     // Perform any initialization here. If you don't then there is no point in implementing init at all. 
    } 
    return self; 
} 
- (void)push:(id)obj 
{ 
    [self addObject:obj]; 
} 
- (id)pop 
{ 
    id lastobj = [self lastObject]; 
    [self removeLastObject]; 
    return lastobj; 
} 
- (BOOL)isEmpty 
{ 
    return [self count] == 0; 
} 
@end