簡體   English   中英

有關在Objective-C中創建類的問題

[英]Question about creating classes in Objective-C

我對目標C真的很陌生,我想創建一個NSDictionary的NSArray類,然后提供一個捕獲隨機條目的方法。 我知道如何做到這一點,但我不理解如何在課堂上做到這一點。 我的意思是,我認為您可以將聲明了該數組(或任何正確的術語)的代碼放在實現文件的中間,然后在此之下編寫一個方法。 我擁有的唯一實例變量是NSArray,它位於接口文件中,以及方法原型(或其他方法),而這些是接口文件中唯一的東西。

我無法弄清問題,所以我做了一個測試類,但是只有一個簡單的文本字符串數組。 我在這里使用了相同的邏輯,但我可以肯定它是完全落后的,但是我不知道以哪種方式。

這是測試類的接口:

#import <Foundation/Foundation.h>


@interface TestClass : NSObject {
    NSArray *TestArray;
}


@end

這是實現文件

#import "TestClass.h"


@implementation TestClass{
    NSArray *TestArray;
}
TestArray = [[NSArray alloc] arrayWithObjects:@"stuff",@"things",@"example",@"stuffThings",nil];

@end

您應該真正閱讀Apple對Objective-C的介紹 它解釋了該語言的語法和結構。 您還必須閱讀《 Objective-C內存管理指南》,以確保程序不會泄漏內存並導致崩潰。

話雖如此,這可能是您要嘗試創建的(我自由更改了一些變量名):

TestClass.h

#import <Foundation/Foundation.h>

@interface TestClass : NSObject {
  NSArray* strings_;
}

// Method declarations would go here
// example:
- (NSString*)randomElement;

@end

TestClass.m

#import "TestClass.h"
#import <stdlib.h>

// Notice how the implementation does NOT redefine the instance variables.
@implementation TestClass

// All code must be in a method definition.

// init is analogous to the default constructor in other languages
- (id)init {
  if (self = [super init]) {
    strings_ = [[NSArray alloc] initWithObjects:@"stuff", @"things", nil];
  }
  return self;
}

// dealloc is the destructor (note the call to super).
- (void)dealloc {
  [strings_ release];
  [super dealloc];
}

- (NSString*)randomElement {
  NSUInteger index = arc4random() % [strings_ count];
  return [strings_ objectAtIndex:index];
}

@end

對於隨機數生成 ,使用arc4random()很容易,因為它不需要設置種子值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM