问题
In Objective-C, the compiler is complaining about the following line of code:
if ([self getLength(self.identifier)] < givenWidth * kMarginAllowance)
This is getting the error "Expected ']'", and the caret below the text is on the parenthesis exactly after "getLength".
My suspicion is that my [self getLength(self.identifier)] is wrong in how it combines things.
What I want to say is "Fetch this object's identifier, and call this object's getLength() method."
I've tried a couple of permutations, and I don't think I'm using correct syntax.
What is the correct syntax for this type of thing?
--
My code is:
-(float)getLength:(NSString *)text
{
UIFont *font = [UIFont fontWithName:@"Scurlock" size:20];
CGSize size = [text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil]];
return size.width;
}
-(void)getFormattedString:(float)givenHeight width:(float)givenWidth
{
NSMutableArray *workbench = [NSMutableArray array];
if (getLength(self.identifier) < givenWidth * kMarginAllowance)
{
[workbench addObject:self.identifier];
}
else
{
// [Under development]
}
}
The included .h file has:
-(float) getLength:(NSString *)text;
There is a yellow warning in Xcode that indicates that the call to getLength() is an invalid implicit declaration. The character it specifically points to is the beginning of the getLength() call. If I try to run it, I get an "Apple Mach-O Linker Error", because _getLength is referenced and presumably doesn't turn anything up.
What is the root problem I'm causing here? Inlining the method might do what I want, but I'd rather fix it, and understand what the correct approach is.
回答1:
Try
[self getLenght:self.identifier]
So it would be like this:
if ([self getLenght:self.identifier] < givenWidth * kMarginAllowance)
getLenght:
is an Objective-C method but you're trying to call it as a C function.
Hope this helps!
回答2:
if ( getLength(self.identifier) < (givenWidth * kMarginAllowance))
回答3:
If getLength
is an instance method
// calls getLength method on self.identifier
if ([self.identifier getLength] < givenWidth * kMarginAllowance)
if it is a C style function
if (getLength(self.identifier) < givenWidth * kMarginAllowance)
来源:https://stackoverflow.com/questions/18963566/how-should-i-be-sending-a-message-with-a-field-of-the-same-object-as-its-value