I am a newbie in programming, currently across some difficulties in my first school work. Can anyone tell me am I doing on the right track? The aim of this code is to do add two numbers around 70 digits which cannot be done using the int or long int type in Objective-C. The following code keeps getting warning: incompatible pointer types returning ‘NSString *__strong’ from a result type ‘MPInteger *’ Help please, I have already been figuring out for ages and got nothing.
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;
}
You declare your method to return an MPInteger:
but you finally return
description, which is anNSStringinstance.You perhaps meant to make an MPInteger instance out of the string before returning:
(add
autoreleaseif you don’t use ARC).