gpt4 book ai didi

objective-c - 无法将对象添加到 NSMutableArray

转载 作者:行者123 更新时间:2023-12-03 17:30:54 25 4
gpt4 key购买 nike

我检查了 Google,但没有找到任何有帮助的信息。我正在用 Objective-C 编写一个堆栈类,该堆栈基于 NSMutableArray,但是,我无法向其中添加任何对象,它不会在控制台中抛出任何错误,并且没有编译警告/错误。这是我的堆栈对象的代码。

#import "Stack.h"

@implementation Stack
@synthesize stack;

- (id)init {
self.stack = [[NSMutableArray alloc] init];
return self;
}

- (void)push:(id)object { [self.stack addObject:object]; }

- (int)size { return [self.stack count]; }

- (id)pop {
id obj = [[[self.stack lastObject] retain] autorelease];
[self.stack removeLastObject];
return obj;
}

- (id)peek { return [self.stack lastObject]; }

@end

标题:

#import <Cocoa/Cocoa.h>

@interface Stack : NSObject {
NSMutableArray *stack;
}

- (void)push:(id)object;
- (int)size;
- (id)pop;
- (id)peek;

@property (nonatomic, retain) NSMutableArray *stack;

@end

对于代码的其余部分,如果我调用 [test_stack size],它会返回零,无论我推送一个对象多少次,如果我调用 pop 或 peek,它只会返回 (null)。

#import "TRIAL_Stack_Ctrl.h"


@implementation TRIAL_Stack_Ctrl
@synthesize test;

- (IBAction)push:(id)sender {
[test_stack push:[input stringValue]];
}
- (IBAction)pop:(id)sender {
[label setStringValue:[NSString stringWithFormat:@"%@", [test_stack pop]]];
}
- (IBAction)peek:(id)sender {
[label setStringValue:[NSString stringWithFormat:@"%@", [test_stack peek]]];
}
- (IBAction)size:(id)sender {
[label setStringValue:[NSString stringWithFormat:@"%d", [test_stack size]]];
}

@end

这让我相信它没有插入物体,我做错了什么吗?

最佳答案

更改:

- (id)init {
self.stack = [[NSMutableArray alloc] init];
return self;
}

至:

- (id)init {
self = [super init];
if (self) {
stack = [[NSMutableArray alloc] init];
}
return self;
}

关于objective-c - 无法将对象添加到 NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3160341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com