gpt4 book ai didi

ios - 我如何在一个类中使用另一个类中的 NSMutablearray?

转载 作者:行者123 更新时间:2023-11-28 22:23:25 24 4
gpt4 key购买 nike

我创建了一个模型,我想保存一些我需要能够在其他两个类中访问的数据。我已经尝试在尝试向其添加 self 之前和之后记录我的数组,但它在之前和之后都是空的。我已经尝试了我能想到的一切,加上大量的谷歌搜索,但我无法让它发挥作用。这是我创建的模型,用于将一些数据存储到:

//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

//CC模型.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

这是我试图从中访问 NSMutableArray 的类

//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

//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];
}


}

}
}

正如您在 if (!self.model.selectedLetters) block 中所见,如果数组是未初始化。否则,我添加对象。我正在尝试使用 objective-c,但对这门语言还是个新手,所以我确信这个过程中有一些我不会放弃理解的简单内容。

最佳答案

另外 2 位发帖者指出了您的代码的 2 个问题。 (不实例化 CCModel 对象,并调用 [NSMutableArray init] 而不是 [[NSMutableArray alloc] init]。

您的代码的第三个问题是这一行:

[self.model.selectedLetters arrayByAddingObject:self];

没有意义。该行代码创建了一个新的不可变数组,然后您将其放在地板上。解决其他 2 个问题后,您想使用这样的代码

[self.model.selectedLetters addObject: self];

你真的要将“self”添加到数组中吗? (一个 SKLetterNode 对象)

关于ios - 我如何在一个类中使用另一个类中的 NSMutablearray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19671990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com