Skip to content

Instantly share code, notes, and snippets.

@greghelton
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greghelton/f5e79c2f8b6ed2d90673 to your computer and use it in GitHub Desktop.
Save greghelton/f5e79c2f8b6ed2d90673 to your computer and use it in GitHub Desktop.
CodeSchool's Try Objective C task to modify copyWithZone method to use id instead of Phone * on the definition of the variable named copy. This code runs ok but does not pass CodeSchool's verification. The error CodeSchool reports when this code is run is: Did not refactor the copyWithZone: method to use the generic id type instead of Phone *
#import "Phone.h"
Phone *talkingiPhone = [[Phone alloc] init];
talkingiPhone.phoneName = @"Mr. Higgie";
[talkingiPhone decreaseBatteryLife:@5];
Phone *copy = [talkingiPhone copy];
[copy reportBatteryLife];
Phone.m[19]: Mr. Higgie
Phone.m[33]: Copy of Mr. Higgie's battery life is 95
@interface Phone : NSObject <NSCopying> {
NSNumber *_batteryLife;
}
@property NSString *phoneName;
@property NSString *modelNumber;
- (Phone *)initWithBatteryLife:(NSNumber *)batteryLife;
- (void) decreaseBatteryLife:(NSNumber *)arg;
- (NSString *) speak:(NSString *)greeting;
- (void) reportBatteryLife;
@end
#import "Phone.h"
@implementation Phone
- (Phone *)init;
{
_batteryLife = @100;
return [super init];
}
- (Phone *)initWithBatteryLife:(NSNumber *)batteryLife;
{
_batteryLife = batteryLife;
return [super init];
}
- (Phone *) copyWithZone:(NSZone *)zone;
{
NSLog(@"%@", [self phoneName]);
id copy = [[[self class] allocWithZone:zone] initWithBatteryLife:_batteryLife];
[copy setPhoneName:[NSString stringWithFormat:@"Copy of %@", [self phoneName]]];
return copy;
}
- (void) decreaseBatteryLife:(NSNumber *)arg;
{
_batteryLife = @([_batteryLife intValue] - [arg intValue]);
}
- (void) reportBatteryLife;
{
if(self.phoneName){
NSLog(@"%@'s battery life is %@", self.phoneName, _batteryLife);
}else{
NSLog(@"%@'s battery life is %@", self, _batteryLife);
}
}
- (NSString *)speak:(NSString *)greeting;
{
NSString *message = [NSString stringWithFormat:@"%@ says %@", self.phoneName, greeting];
return message;
}
@end
- (id) copyWithZone:(NSZone *)zone;
{
NSLog(@"%@", [self phoneName]);
id copy = [[[self class] allocWithZone:zone] initWithBatteryLife:_batteryLife];
[copy setPhoneName:[NSString stringWithFormat:@"Copy of %@", [self phoneName]]];
return copy;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment