Reputation: 59
I am trying to write a method for a new class called "word", which is a subclass of NSString. I want a method that will accept a NSString containing a single character and return the the place within the word of every instance of that string. I have this so far:
@implementation Word
-(NSMutableArray *)placeOfLetter: (NSString *)letterAsked;{
NSUInteger *len=(NSUInteger *)[self length];
int y=0;
char letter=(char)letterAsked;
for (NSUInteger *x=0; x<len; x++) {
if ([self characterAtIndex:*x]==letter){
[matchingLetters insertObject:x atIndex:y];
y++;
}
}
}
@end
however, xcode is telling me that I cannot put x as a the parameter for insertObject, because the "implicit conversion from NSUInteger to id is disallowed. How can I get around this?
Upvotes: 0
Views: 133
Reputation: 385500
NSUInteger
is a typedef
for either unsigned int
or unsigned long
, depending on your platform. It is not an object type. So when you declare NSUInteger *x=0
, you're declaring x
as a pointer-to-unsigned-integer, and initializing it to null.
The insertObject:atIndex:
requires an NSUInteger
, not an NSUInteger*
, as its index
argument.
Just take out the *
from the for
statement and the characterAtIndex:
message.
You do have other problems in your method also, like casting letterAsked
to a char
instead of getting the character out of it using characterAtIndex:
and declaring len
as a pointer.
Upvotes: 1
Reputation: 60110
The problem you're encountering is stemming mostly from your treating NSUInteger
as a pointer; you have some other casting problems as well. Try the following:
letterAsked
argument, then getting a char
out of it, just get a char
(or unichar
) as your argument to begin with. You avoid the letter = (char)letterAsked
conversion altogether.Don't make len
a pointer. You may not need to declare len
at all. Consider writing your for
loop like:
for(NSUInteger x = 0; x < [self length]; x++) { // ...
This also helps you in the -characterAtIndex:
call; you no longer need to dereference x
in order to get the character.
Like Hot Licks said in the comments, use an NSNumber if you want a position inside an NSArray; you need numbers to be class instances to go in an NSArray instance. You can create an NSNumber out of x
like this:
NSNumber * foundPosition = [NSNumber numberWithUnsignedInteger:x];
Consider just using NSMutableArray's -addObject:
method, rather than keeping track of y
and incrementing it each time. You'll get the same result.
Upvotes: 2