如何在Stack中存储NSString

时间:2013-04-18 12:25:07

标签: ios objective-c uitableview 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的类 我想什么时候点击从URL

接收的TableViewController商店单元格的id中的单元格

这是我的代码:

- (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),但我不知道如何使用堆栈。

2 个答案:

答案 0 :(得分:1)

  1. 你需要一个保存你的堆栈的变量..我会把它变成一个成员var:

    @implementation TableViewController {
        Stack *_stack;
    }
    ...
    
  2. 然后单击单元格时,按下值

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

答案 1 :(得分: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