开发者

Question about creating classes in Objective-C

开发者 https://www.devze.com 2023-01-12 03:56 出处:网络
I am really new to objective C, and I want to make a class that is an NSArray of NSDictionary, and then have a method that grabs a random entries.I know how to make that but I don\'t understand how to

I am really new to objective C, and I want to make a class that is an NSArray of NSDictionary, and then have a method that grabs a random entries. I know how to make that but I don't understand how to make it in the class. What I mean is I thought that you could put the code that declared (or whatever the correct terminology is) the array just sort of in the middle of the implementation开发者_运维知识库 file and then I would write a method under that. The only instance variable I had was the NSArray and that was in the interface file, along with the method prototype (or whatever) and these were the only things that were in the interface file.

I couldn't figure out the problem so I made a test class that was the same but with just an array of simple text strings. I used the same logic here and I'm pretty certain it is totally backward, I don't know in which way though.

This is the interface for the test class:

#import <Foundation/Foundation.h>


@interface TestClass : NSObject {
    NSArray *TestArray;
}


@end

And this is the implementation file

#import "TestClass.h"


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

@end


You should really read Apple's introduction to Objective-C. It explains the syntax and structure of the language. You must also read the Objective-C memory management guide so that your programs don't leak memory and crash.

Having said that, here's probably what you're trying to create (I took the liberty of changing some of your variable names):

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

For random number generation, it's easy to use arc4random() because it doesn't require setting the seed value.

0

精彩评论

暂无评论...
验证码 换一张
取 消