我正在为 ios 使用 objective c 编程。我有问题...我创建了一个类对象 这是 Item.h
@interface Item : NSObject {
NSString *date;
NSMutableArray *a;
NSMutableArray *b;
NSMutableArray *c;
NSMutableArray *d;
NSMutableArray *e;
NSMutableArray *f;
NSMutableArray *g;}
- (id)init;
- (void)setDate:(NSString *)dateGio;
- (void)adda:(NSString *)i;
- (void)addb:(NSString *)i;
- (void)addc:(NSString *)i;
- (void)addd:(NSString *)i;
- (void)adee:(NSString *)i;
- (void)addf:(NSString *)i;
- (void)addg:(NSString *)i;
- (NSMutableArray *)geta;
- (NSMutableArray *)getb;
- (NSMutableArray *)getc;
- (NSMutableArray *)getd;
- (NSMutableArray *)gete;
- (NSMutableArray *)getf;
- (NSMutableArray *)getg;
@end
这是Item.m
#import "MealsItem.h"
@implementation MealsItem
- (id)init {
self = [super init];
if(self) {
NSString *date = @"";
NSMutableArray *a = [[NSMutableArray alloc] init];
NSMutableArray *b = [[NSMutableArray alloc] init];
NSMutableArray *c = [[NSMutableArray alloc] init];
NSMutableArray *d = [[NSMutableArray alloc] init];
NSMutableArray *e = [[NSMutableArray alloc] init];
NSMutableArray *f = [[NSMutableArray alloc] init];
NSMutableArray *g = [[NSMutableArray alloc] init];
}
return self;
}
- (void)adda:(NSString *)i {
[a addObject: i];
}
- (void)addb:(NSString *)i {
[b addObject: i];
}
- (void)addb:(NSString *)i {
[b addObject: i];
}
- (void)addd:(NSString *)i {
[d addObject: i];
}
- (void)adde:(NSString *)i {
[e addObject: i];
}
- (void)addf:(NSString *)i {
[f addObject: i];
}
- (void)addg:(NSString *)i {
[g addObject: i];
}
- (NSMutableArray *)geta {
return a;
}
- (NSMutableArray *)getb {
return b;
}
- (NSMutableArray *)getc {
return c;
}
- (NSMutableArray *)getd {
return d;
}
- (NSMutableArray *)gete {
return e;
}
- (NSMutableArray *)getf {
return f;
}
- (NSMutableArray *)getg {
return g;
}
@end
在这个对象中,我将字符串保存在特定的数组中。在我的第一个 View (项目的主要部分)中,我初始化了对象
#import <UIKit/UIKit.h>
#import "Item.h"
@interface First_View : UIViewController {
@public Item *ok;
}
@property (nonatomic, retain) Item *ok;
@end
在 .m 中
#import "First_View.h"
#import "Item.h"
@interface First_View ()
@end
@implementation First_View
@synthesize ok;
- (void)viewDidLoad
{
[super viewDidLoad];
ok = [[Item alloc] init];
}
@end
问题是我必须从另一个类使用“Item.m”的方法读取和修改在 First_View 中初始化的对象。在另一个类(class)我用这个
First_View *first = [[First_View alloc] init];
我尝试修改对象,但我做不到。我可以,只要我也用
first.ok = [[Item alloc] init];
但我不想再次初始化该对象,而是使用已在 First_View 中创建的对象。如何在不重新初始化对象的情况下修改对象?
最佳答案
Item.m/Item.h 中的代码对我来说没有任何意义。
您正在尝试声明名为 1、2、3、4、5、6、7 的实例变量。这是无稽之谈。
您明确声明了 getter 和 setter 方法。那只是在给自己制造不必要的工作。只需使用@property。
您的 init 方法并不像您认为的那样工作。它创建新对象,但不将它们分配给实例变量,而是分配给 init 方法中的局部变量。这意味着一旦 init 返回,它们就会丢失。并且您试图将这些变量命名为 1、2、3、4、5、6、7,这是非法和无意义的。
“早餐”等从何而来?
关于ios - 如何使用 Objective-C 创建和使用对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22303628/