I want to self assign an adjusted nsstring via category.
The example is a trim function:
I do not want that way:
NSString *theTempString = [theExampleString xTrim];
// ... go on doing stuff with theTempString
I want it this way:
[theExampleString xTrim];
// ... go on doing stuff with theExmapleString
The category looks like this:
- (void)xTrim
{
self = [self stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
}
The error that an assignment outside init is not possible - I understand that.
But now I'm interested in it, of course I can write an custom init methode, but is there no way around it like the one above???
Greetings and thanks,
matthias
You don't need to create a new NSString, the method already does that for you:
- (NSString *)xTrim
{
return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
NSString is immutable so you need to assign it:
yourString = [yourString xTrim];
You cannot do that in a category on NSString, because NSString manages immutable strings, which means that the string can not be changed after it has been created.
You could implement it as category on NSMutableString:
- (void)xTrim
{
NSString *trimmed = [self stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
[self setString:trimmed]; // replaces the characters of "self" with those of "trimmed".
}
And if your question is: Can I write a method xTrim such that
[theExampleString xTrim]
replaces the receiver theExampleString with a new instance: No, that is not possible.
Related
NSMutableString *chars=[ [NSMutableString alloc] initWithString:#""] ;
NSString *temp=[[self convertDecimalToChar:(digitizer%10)] copy]; //temp is good
[chars stringByAppendingString:temp]; //chars is empty
Any idea whats wrong here ?
Thank you.
This line:
[chars stringByAppendingString:temp];
Is supossed to return a string combining both strings.
- (NSString *)stringByAppendingString:(NSString *)aString
If you want to just append a string to your string, do this:
[chars appendString:temp];
Find the documentation here:
NSmutableString
The stringByAppendingString method is on the non-mutable NSString class, where non-mutable means you cannot modify it.
Therefore, as with most other NSString methods, it returns a new NSString object, in this case containing the original string plus whatever you passed in the parameter.
However given you are actually manipulating an NSMutableString object, which is mutable, you probably want the appendString: method instead:
[chars appendString:temp];
If you take a look at the documentation of this method, you need to do:
chars = [chars stringByAppendingString:temp];
It is returning a new NSString combining the two NSString, not actually changing the receiver.
I'm trying to change a variable of NSString type by calling a method. But it doesn't work. I tried this very same method with othe types and it worked perfectly fine. Can you help me out there?
Interface:
- (void) changeNSString: (NSString *) stringToChange;
Implementation:
- (void) changeNSString: (NSString *) stringToChange{
stringToChange = #"Test";
}
- (IBAction)actionBla:(id)sender {
NSString *myString = [NSString string];
[self changeNSString:myString];
NSLog(myString); //Returns nothing or empty string
}
======================
Edit: thanks to the help of CrimsonDiego, here is a working solution. Though I still have a little understanding issue: why is there no type-error when assigning a NSMutableString to a NSString var?
Interface:
- (void) changeNSMutableString: (NSMutableString *) stringToChange;
Implementation:
- (void) changeNSMutableString: (NSMutableString *) stringToChange{
[stringToChange setString:#"Test"]
}
- (IBAction)actionBla:(id)sender {
NSMutableString *myString = [NSMutableString string];
[self changeNSMutableString:myString];
self.myLabel.text = myString; //Why is there no type error???
}
You are assigning a new variable to a local variable within the function.
The local variable stringToChange references the same variable as myString at first, but when you assign #"Test" to stringToChange, it no longer references the original string.
The solution here would be to use NSMutableString, or have a class variable (or property) and use that instead of passing it to the function.
Your setting stringToChange as local in your function. Try the following:
- (NSString*) changeNSString: (NSString *) stringToChange{
stringToChange = #"Test";
return stringToChange;
}
- (IBAction)actionBla:(id)sender {
NSString *myString = [NSString string];
myString = [self changeNSString:myString];
NSLog(myString); //Returns nothing or empty string
}
I am no expert on Objective-C but it seems to me that stringToChange, as in "normal" C, is a parameter that can contain a pointer to a string. The parameter is pass-by-value and thus, when you assign #"Test" to stringToChange you are actually only changing the local parameter stringToChange and not myString. If you want to change myString you have to change the parameter type to NSString ** and pass &myString as a parameter instead.
I have an array of strings, from which I would like to extract only those with unique character sets. (For example, "asdf" and "fdsa" would be considered redundant). This is the method I am currently using:
NSMutableArray *uniqueCharSets = [[NSMutableArray alloc] init];
NSMutableArray *uniqueStrings = [[NSMutableArray alloc] init];
for (NSString *_string in unique) {
NSCharacterSet *_charSet = [NSCharacterSet characterSetWithCharactersInString:_string];
if (![uniqueCharSets containsObject:_charSet]) {
[uniqueStrings addobject:_string];
[uniqueCharSets addObject:_charSet];
}
}
This seems to work, but it's very slow and resource-intensive. Can anyone think of a better way to do this?
Using an NSDictionary, map each string's lexicographically-sorted equivalent to an NSArray of input strings: (e.g. adfs => [afsd, asdf, ...])
Walk through the dictionary, printing out keys (or their values) which only have single-element array values
I just put together a quick example of how I would approach this, but it turns out that it is more, odd, than you first expect. For one, NSCharacterSet doesn't implement equality to check contents. It only uses the pointer value. Based on this your example will NOT work properly.
My approach is to use an NSSet to deal with the hashing of these for us.
#interface StringWrapper : NSObject
#property (nonatomic, copy) NSString *string;
#property (nonatomic, copy) NSData *charSetBitmap;
- (id)initWithString:(NSString*)aString;
#end
#implementation StringWrapper
#synthesize string, charSetBitmap;
- (id)initWithString:(NSString*)aString;
{
if ((self = [super init]))
{
self.string = aString;
}
return self;
}
- (void)setString:(NSString *)aString;
{
string = [aString copy];
self.charSetBitmap = [[NSCharacterSet characterSetWithCharactersInString:aString] bitmapRepresentation];
}
- (BOOL)isEqual:(id)object;
{
return [self.charSetBitmap isEqual:[object charSetBitmap]];
}
- (NSUInteger)hash;
{
return [self.charSetBitmap hash];
}
#end
int main (int argc, const char * argv[])
{
#autoreleasepool {
NSMutableSet *stringWrappers = [[NSMutableSet alloc] init];
NSArray *strings = [NSArray arrayWithObjects:#"abc",#"aaabcccc",#"awea",#"awer",#"abcde", #"ehra", #"QWEQ", #"werawe", nil];
for (NSString *str in strings)
[stringWrappers addObject:[[StringWrapper alloc] initWithString:str]];
NSArray *uniqueStrings = [stringWrappers valueForKey:#"string"];
NSLog(#"%#", uniqueStrings);
}
return 0;
}
The code is pretty straightforward. We create a container object to cache the results of the character set's bitmap representation. We use the bitmap representation because NSData implements isEqual: appropriately.
The only thing that come in my mind is not to use containsObject: since NSMutableArray is not ordered (in general), we can assume that containsObject simply iterates the array starting from the beginning until he finds the object. This means O(n) (n comparisons in the worst case).
A better solution may consists in keeping the array ordered and use a custom search method using a dichotomic approach. This way you'll have a O(log n) complexity.
Of course, you must take care of keeping your array ordered (much more efficient than add and reorder), so you should use insertObject:atIndex: method to insert the element properly.
#interface MainView : UIView {
NSMutableString *mutableString;
}
#property (nonatomic, retain) NSMutableString *mutableString;
#end
#implementation MainView
#synthesize mutableString;
-(void) InitFunc {
self.mutableString=[[NSMutableString alloc] init];
}
-(void) AppendFunc:(*NString) alpha {
[self.mutableString stringByAppendingString:#"hello"];
NSLog(#"the appended String is: %#",self.mutableString);
int len=[self.mutableString length];
}
Hey Everyone,
i just want to know where I am doing wrong ??? . I tried this code but "mutableString" does not append any value (as value of "len"comes '0' and NSLog doesnt print any value for "mutableString"), though i ve searched on net for the solution, people implemented in the same fashion yet i dont know why my code isnt working.
Thanks in Advance
MGD
stringByAppendingString: creates new string. Use appendString: instead:
[mutableString appendString:#"hello"]
1) Your method names violate the naming conventions: use lower case letters to start with.
2) stringByAppendingString returns a new string as a result and doesn't modify your original. You should use [self.mutableString appendString:#"hello"]; instead.
3) Your init method is leaking. You should use mutableString = [[NSMutableString alloc] init]; and not use the dot syntax, as it will be retained otherwise (and a release would be missing).
Oh God, what a mess. The stringByAppendingString does not change the string, it creates and returns a new one:
// Sets str2 to “hello, world”, does not change str1.
NSMutableString *str1 = [NSMutableString stringWithString:#"hello, "];
NSString *str2 = [str1 stringByAppendingString:#"world"];
If you want to change the mutable string itself, use the appendString method:
// Does not return anything, changes str1 in place.
[str1 appendString:#"world"];
Also, this is a leak:
self.mutableString = [[NSMutableString alloc] init];
This is best written as:
mutableString = [[NSMutableString alloc] init];
…because using accessors in init and dealloc is not the best idea.
I want to compare the value of an NSString to the string "Wrong". Here is my code:
NSString *wrongTxt = [[NSString alloc] initWithFormat:#"Wrong"];
if( [statusString isEqualToString:wrongTxt] ){
doSomething;
}
Do I really have to create an NSString for "Wrong"?
Also, can I compare the value of a UILabel's text to a string without assigning the label value to a string?
Do I really have to create an NSString for "Wrong"?
No, why not just do:
if([statusString isEqualToString:#"Wrong"]){
//doSomething;
}
Using #"" simply creates a string literal, which is a valid NSString.
Also, can I compare the value of a UILabel.text to a string without assigning the label value to a string?
Yes, you can do something like:
UILabel *label = ...;
if([someString isEqualToString:label.text]) {
// Do stuff here
}
if ([statusString isEqualToString:#"Wrong"]) {
// do something
}
Brian, also worth throwing in here - the others are of course correct that you don't need to declare a string variable. However, next time you want to declare a string you don't need to do the following:
NSString *myString = [[NSString alloc] initWithFormat:#"SomeText"];
Although the above does work, it provides a retained NSString variable which you will then need to explicitly release after you've finished using it.
Next time you want a string variable you can use the "#" symbol in a much more convenient way:
NSString *myString = #"SomeText";
This will be autoreleased when you've finished with it so you'll avoid memory leaks too...
Hope that helps!
You can also use the NSString class methods which will also create an autoreleased instance and have more options like string formatting:
NSString *myString = [NSString stringWithString:#"abc"];
NSString *myString = [NSString stringWithFormat:#"abc %d efg", 42];