自我和数组问题

时间:2013-08-28 02:37:03

标签: objective-c

我是Objective C的新手,我无法理解一些事情。

我正在尝试创建一个大整数程序,我从中读取字符串中输入的项目并将它们放入数组中的单个元素中。

我目前正在研究一种add方法,该方法将两个数组中的元素一起添加到最终数组中。

但我有点困惑,将我从initWithString方法制作的数组放入数组方法中。我对自己有一些了解,但我不知道如何在这个意义上使用它。

    @implementation MPInteger

    {    
    }

    -(id) initWithString: (NSString *) x
    {
        self = [super init];
        if (self) {
        NSMutableArray *intString = [NSMutableArray array];
        for (int i = 0; i < [x length]; i++) {
            NSString *ch = [x substringWithRange:NSMakeRange(i, 1)];
            [intString addObject:ch];
        }
        }
        return self;
    }

    -(NSString *) description
    {
        return self.description;
    }


-(MPInteger *) add: (MPInteger *) x
{
    //NSMutableArray *arr1 = [NSMutableArray arrayWithCapacity:100];
    //NSMutableArray *arr2 = [NSMutableArray arrayWithCapacity:100];
    //for (int i=0; i < 100; i++) {
        //int r = arc4random_uniform(1000);
        //NSNumber *n = [NSNumber numberWithInteger:r];
        //[arr1 addObject:n];
        //[arr2 addObject:n];

   // }

    self.array = [NSMutableArray initialize];




    return x;


}

@end



int main(int argc, const char * argv[]) {

    @autoreleasepool {
        MPInteger *x = [[MPInteger alloc] initWithString:@"123456789"];
        MPInteger *y = [[MPInteger alloc] initWithString:@"123456789"];

        [x add: y];

    }
}

所以我想添加x和y数组,但我不知道如何在add方法中获取数组。我是使用self来表示其中一个数组并对其进行初始化,而使用x来表示另一个数组。我不知道我是不是完全走错了路。一些有助于理解的人将不胜感激。

1 个答案:

答案 0 :(得分:0)

当提到 self 时,您实际上正在访问该类的当前实例。在其他语言中,这可以实现为 this 。有几种方法可以设计你想要的方法,但最简单的模式可能是组合:

@interface MPInteger
{
  NSMutableArray *digits;
}

@end

---------------------------------------------------------------------------- 

@implementation MPInteger

-(id) initWithString: (NSString *) x
{
    // Create a new instance of this class (MPInteger) with a default
    // constructor and assign it to the current instance (self).
    self = [super init];
    if (self) {

    // Previously we initialized a string, but then threw it out!
    // Instead, let's save it to our string representation:
    self->digits = [NSMutableArray array];
    for (int i = 0; i < [x length]; i++) {
        NSString *ch = [x substringWithRange:NSMakeRange(i, 1)];
        [self->digits addObject:ch];
    }
    return self;
}

// Depending on how you want to implement this function, it could return
// a new MPInteger class or update the current instance (self):
-(MPInteger *) add: (MPInteger *) x
{
    NSArray *a = self->digits;
    NSArray *b = x->digits;

    // Have both strings for A + B, so use them to find C:
    NSArray *c = ????;

    // Return a new instance of MPInteger with the result:
    return [ [ MPInteger alloc ] initWithString:c ];
}

@end

请注意,现在MPInteger类具有一个NSString对象的实例,该实例将在MPInteger对象的整个生命周期内存在。要更新/访问此字符串,您只需说:

self->digits
相关问题