我創建了一個模型,我想保存一些我需要能夠在另外兩個類中訪問的數據。 我試過在嘗試向它添加self
之前和之後嘗試記錄我的數組,但它在前後都是空的。我試過所有我能想到的,加上大量的谷歌搜索,但我無法得到這個工作。 這裏是我的模型,我創建了一些數據存儲到:如何在另一個類中使用一個類的NSMutablearray?
// CCModel.h
#import <Foundation/Foundation.h>
@interface CCModel : NSObject
// this is the array that I want to store my SKLetterNodes in
@property(strong, nonatomic) NSMutableArray* selectedLetters;
@end
// CCModel.m
#import "CCModel.h"
@implementation CCModel
- (id)init
{
self = [super init];
if (self) {
// not really to sure if this is the right approach to init the array that I'm going to need
self.selectedLetters = [NSMutableArray init];
}
return self;
}
@end
這裏有我想要的類從
// SKLetterNode.h
#import <SpriteKit/SpriteKit.h>
#import "CCModel.h"
@class SKLetterNode;
@protocol LetterDragDelegateProtocol <NSObject>
-(void)letterNode:(SKLetterNode*)letterNode didDragToPoint:(CGPoint)pt;
@end
@protocol LetterWasTouchedDelegateProtocol <NSObject>
-(void) touchedPoint:(CGPoint)touchedPoint;
@end
@interface SKLetterNode : SKSpriteNode
// Here is where I'm creating a property to access my model's NSMutableArray
@property(strong, nonatomic) CCModel* model;
....
@end
0123訪問的NSMutableArray
// SKLetterNode.m - 我就包括相關的方法,因爲一切在這個類
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (!self.isSelected) {
SKLetterNode* lastLetter = [self.model.selectedLetters lastObject];
if (lastLetter.bottomOrTop != self.bottomOrTop || self.model.selectedLetters.count == 0) {
CGSize expandSize = CGSizeMake(self.size.width * expandFactor, self.size.height * expandFactor);
SKAction* sound = [SKAction playSoundFileNamed:@"button.wav" waitForCompletion:NO];
[self runAction:sound];
self.isSelected = YES;
self.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:expandSize];
self.physicsBody.affectedByGravity = NO;
self.physicsBody.allowsRotation = NO;
if (!self.model.selectedLetters) {
// Here is where I'm trying to init my array by adding an object
[self.model.selectedLetters arrayByAddingObject:self];
} else {
// The array must already be initialized, so add the object
[self.model.selectedLetters addObject:self];
}
}
}
}
正如你可以看到在工作中,如果(!self.model.selectedLetters)
塊,我試圖給init陣列如果數組未初始化,則添加對象self
。否則,我添加該對象。我正在努力學習Objective-C,而且對這門語言仍然很陌生,所以我確信這個過程只是簡單的一件事情,我不會放棄理解。
你在哪裏實例化'model'?如果'''self.model.selectedLetters''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''',不管'selectedLetters'是否被初始化,並且'model'沒有被實例化,一個'模型'的屬性。 – nhgrif