Obj-C变量堆栈类型

时间:2015-03-16 02:47:30

标签: objective-c pointers stack

作为对新编程语言的尝试,我构建了众所周知的数据结构,以熟悉语法和基本内容。出了语言。在这种情况下,我检查Objective-C中的堆栈。从Apple的使用对象,我们读到关键字'id'

  

...这是Objective-C中使用的一个特殊关键字,意思是“某种对象。”它是一个指向对象的指针,如(NSObject *),但它的特殊之处在于它不使用星号。

通过使用关键字“id”,似乎可以创建一个包含不同类型的Obj-C对象的堆栈数据结构;但是,我不确定这是否符合预期。为每种潜在的数据类型创建各种类方法是否更好,而不是尝试通用方法并确保每个堆栈遵循单个对象类型?这是我到目前为止所拥有的

XYZNode.h

#import <Foundation/Foundation.h>

@interface XYZNode : NSObject

@property id value;

@property XYZNode *next;

-(instancetype)initWithValue:(id)aValue next:(XYZNode *)aNext;

-(instancetype)init;

//  Class factory methods should always start with the name of 
//  the class (without the prefix) that they create, with the 
//  exception of subclasses of classes with existing factory methods.
+(XYZNode *)nodeWithValue:(id)aValue nextNode:(XYZNode *)aNext;

@end

XYZNode.m

#import "XYZNode.h"

@implementation XYZNode

-(instancetype)initWithValue:(id)aValue next:(XYZNode *)aNext {

    if (self = [super init]) {
        _value = aValue;
        _next = aNext;
    } return self;

}

-(instancetype)init {

    return [self initWithValue:nil next:nil];

}

+(XYZNode *)nodeWithValue:(id)aValue nextNode:(XYZNode *)aNext {

    return [[self alloc] initWithValue:aValue next:aNext];

}

@end

XYZStack.h

#import <Foundation/Foundation.h>

@interface XYZStack : NSObject

-(void)pushValue:(id)aValue;

-(id)popValue;

-(BOOL)isEmpty;

-(instancetype)init;

-(instancetype)initWithValue:(id)aValue;

+(XYZStack *)stackWithValue:(id)aValue;

@end

XYZStack.m

#import "XYZStack.h"

#import "XYZNode.h"

// The extension hides how the values are stored
@interface XYZStack ()

@property XYZNode *lastNodeAdded;

@end

@implementation XYZStack

// Default initializer
-(instancetype)initWithValue:(id)aValue {

    if (self = [super init]) {

        _lastNodeAdded = nil;

    }

    if (aValue) {

        [self pushValue:aValue];

    }

    return self;
}

// Call default initializer
-(instancetype)init{

    return [self initWithValue:nil];
}

-(BOOL)isEmpty{

    return ([self lastNodeAdded] == nil);

}

-(void)pushValue:(id)aValue {

    [self setLastNodeAdded:[XYZNode nodeWithValue:aValue nextNode:[self lastNodeAdded]]];

}

-(id)popValue {

    id temp = [[self lastNodeAdded] value];

    [self setLastNodeAdded:[[self lastNodeAdded] next]];

    return temp;

}

+(XYZStack *)stackWithValue:(id)aValue {

    return [[self alloc] initWithValue:aValue];

}

@end

任何意见将不胜感激。

0 个答案:

没有答案