不兼容的指针类型?

时间:2012-09-01 11:50:38

标签: objective-c

我是编程新手,目前在我的第一次上学工作中遇到了一些困难。任何人都可以告诉我,我在正确的轨道上做什么?此代码的目的是在70位数字之间添加两个数字,这些数字无法使用Objective-C中的int或long int类型完成。以下代码不断收到警告:不兼容的指针类型从结果类型'MPInteger *'返回'NSString * __ strong'请帮助,我已经找了好几年并且一无所获。

MPInteger.h

#import <Foundation/Foundation.h>

@interface MPInteger : NSObject
@property (copy, nonatomic) NSString * description;

-(id) initWithString: (NSString *) x;
-(NSString *) description;
-(MPInteger *) add: (MPInteger *) x;

MPInteger.m

#import "MPInteger.h"

@implementation MPInteger

@synthesize description;

-(id) initWithString: (NSString *) x {
    self = [super init];
    if (self) {
        description = [NSString stringWithString: x];
    }
    return self;
}

-(NSString *) description {
    return description;
}

-(MPInteger *) add: (MPInteger *) x
{
    int carry = 0;
    int index = 0;
    int index2 = 0;
    int i;
    int num1;
    int num2;
    int result;


    index = [description length];
    index2 = [x.description length];


    while (index2 < index) {
        x.description = [x.description stringByPaddingToLength:index withString:@"0" startingAtIndex:0];
    }

    for (i = index; i <= index || carry != 0; i--) {
        num1 = [description characterAtIndex:index];
        num2 = [x.description characterAtIndex:index];
        result = num1 + num2 + carry;
        // if the sum is less than 10
        if (result < 10) {
            NSString *intString = [NSString stringWithFormat:@"%i", result];
            [description replaceValueAtIndex:index inPropertyWithKey:intString withValue:@"%@"];
            // replace the description index value with the sum
        } else { //otherwise
            NSString *intString = [NSString stringWithFormat:@"%i", result];
            //getting the index'1' is the value replace the description index value
            [description replaceValueAtIndex:index inPropertyWithKey:[intString substringFromIndex:1] withValue:@"%@"];
            carry = 1;
        }
        index--; // decrement index
    }
    return description;
}

3 个答案:

答案 0 :(得分:1)

这几乎就是错误所说的:

@property (copy, nonatomic) NSString * description;
[...]
-(MPInteger *) add: (MPInteger *) x
{
[...]
    return description;
}

您说您的add方法会返回对MPInteger对象的引用,但您的代码会返回对NSString的引用。您需要通过为方法声明字符串类型的返回值或返回MPInteger的实例来进行匹配。

答案 1 :(得分:1)

您声明您的方法返回MPInteger:

- (MPInteger *)add:(MPInteger *)other;

但您最终会返回description,这是NSString个实例。

你可能想在返回之前从字符串中创建一个MPInteger实例:

return [[MPInteger alloc] initWithString:description];

(如果您不使用ARC,请添加autorelease。)

答案 2 :(得分:0)

警告是因为您从description方法返回add:,但descriptionNSString。您需要description成为MPInteger

不幸的是,NSObject已经在格式字符串中有方法called说明which returns an NSString . It's this method that's called each time you use%@`,即

NSLog(@"I am %@", self);

实际上会在description上调用self并将其放入字符串中以代替%@

在您的方法结束时,您需要返回MPInteger而不是description。尝试替换

return description;

MPInteger newInteger = [MPInteger new];
newInteger.description = description;
return newInteger;

返回一个新整数。