Append integers to Objective C variable names - ios

I am new to Objective C. What my code currently does is create a new Card object, assigns properties to the object and then adds the Card object to the cards array. The value numberOfCards varies.
for (int i = 0; i < numberOfCards; i++) {
Card *addCard = [Card new];
addCard.balance = [balanceArray objectAtIndex:i];
addCard.date = [dateArray objectAtIndex:i];
addCard.name = [nameArray objectAtIndex:i];
addCard.number = [numberArray objectAtIndex:i];
[cards addObject:addCard];
}
However, what I want to do is give each card a unique name. For example, if numberOfCards was n, then we would get the Card variable names of addCard1, addCard2 ... addCardn.
So how can I append i onto addCard?
Cheers

You mean like this?
NSString *cardName = [[NSString alloc] initWithFormat:#"addCard%i", i + 1];
addCard.name = cardName;

In order to chain a number to a string all you have to do is:
NSString *cardNewName = [NSString stringWithFormat:#"%#%i",cardName,cardNumber];
The idea is to build a format of string and then chain the necessary parameters.
%# is for string
%i is for integer
%f for float
etc.
It's better to use stringWithFormat then [[NSString alloc] initWithFormat:...] - for an extended information please take a look at the following question:
stringWithFormat vs. initWithFormat on NSString

Related

How to convert string into an IP Address?

I am using a function to adding . after every three characters inside the string. But how can i remove "0" in front of number.
-(NSString *)formatStringAsIpAddress:(NSString*)MacAddressWithoutColon
{
NSMutableString *macAddressWithColon = [NSMutableString new];
for (NSUInteger i = 0; i < [MacAddressWithoutColon length]; i++)
{
if (i > 0 && i % 3 == 0)
[macAddressWithColon appendString:#"."];
unichar c = [MacAddressWithoutColon characterAtIndex:i];
[macAddressWithColon appendString:[[NSString alloc] initWithCharacters:&c length:1]];
}
return macAddressWithColon;
}
If i have ip address 010.000.001.016
How can i set it up like 10.0.1.16? and if i have ip address 192.168.001.001? how to remove front 0's from IP address ?
What I would suggest:
NSString *ipAddress = #"010.000.001.016";
Split string into array of substrings:
NSArray *ipAddressComponents = [myString componentsSeparatedByString:#"."];
Run through the array with for loop and convert each to a int representation:
for(int i = 0; i < ipAddressComponents.count;i++)
{
[ipAddressComponents objectAtIndex:i] = [NSString stringWithFormat:#"%d",[[ipAddressComponents objectAtIndex:i]intValue]];
}
Join the array back into a string
NSString *newIpAddress = [ipAddressComponents componentsJoinedByString:#"."];
This should result into getting an IP address: 10.0.1.16
You can use string function and get your expected output with the help of componentsSeparatedByString and componentsJoinedByString functions.
Use below method for the same:
-(NSString*)removeZeroPrefix:(NSString*)aStrIP{
NSMutableArray *subStringArray = [[NSMutableArray alloc] init];
NSArray *arrayOfSubString = [aStrIP componentsSeparatedByString:#"."];
for (NSString *aSingleString in arrayOfSubString)
{
[subStringArray addObject:[NSNumber numberWithInteger:[aSingleString integerValue]]];
}
return [subStringArray componentsJoinedByString:#"."];
}
Usage :
[self removeZeroPrefix:#"010.000.001.016"];
[self removeZeroPrefix:#"192.168.001.001"];
Output :
Printing description of aStrIP:
10.0.1.16
Printing description of aStrIP:
192.168.1.1
hope this will helps!
In Swift
let ip = "0125.052.000.10"
let split = ip.components(separatedBy: ".")
for number in split {
if let isNumber = Int(number){
print(isNumber) // add this isNumber into array which is shows without initial zeros.
}
}
Finally join created array as String with dot Component

Efficiently create placeholder template NSString with NSArray of values

I am trying to make a utility method for FMDB which will take an NSArray of values and return a string of placeholders for use in an IN statement based on the number of values in the array.
I can't think of an elegant way of creating this string, am I missing some NSString utility method:
// The contents of the input aren't important.
NSArray *input = #[#(55), #(33), #(12)];
// Seems clumsy way to do things:
NSInteger size = [input count];
NSMutableArray *placeholderArray = [[NSMutableArray alloc] initWithCapacity:size];
for (NSInteger i = 0; i < size; i++) {
[placeholderArray addObject:#"?"];
}
NSString *output = [placeholderArray componentsJoinedByString:#","];
// Would return #"?,?,?" to be used with input
What about this?
NSArray *input = #[#(55), #(33), #(12)];
NSUInteger count = [input count];
NSString *output = [#"" stringByPaddingToLength:(2*count-1) withString:#"?," startingAtIndex:0];
// Result: ?,?,?
stringByPaddingToLength fills the given string (the empty string in this case)
to the given length by appending characters from the pattern #"?,".

How to collect parameters from a .cgi URL into multiple strings in iOS objC?

I'm trying to collect the parameters from my ip camera and pass them into individual strings in Objective-C (an iOS app). When I enter the following URL in any web browser: [http://192.168.1.10:92/get_camera_params.cgi] the following is displayed onto the screen:
var resolution=32;
var brightness=136;
var contrast=4;
var mode=2;
var flip=3;
var fps=0;
I would like to collect and pass this values into my own strings such as:
myResolution = 32;
myBrightness = 136;
...................
My guess is that I need to somehow convert the response of the URL into a string and somehow break that string into an array of strings or 6 strings and collect the data in between "=" and ";" in individual strings?
Even though the actual values are Int's, the values must be stored in individual strings for my further code compatibility.
As much as it looks easy, I'm not sure how to approach this, I had a good go at it but didn't advance to anything that is worth putting here on the forum.
Please help with an example.
I'd really appreciate it.
if the response ist non-html, the following should work:
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
NSCharacterSet* charSetToReplace = [NSCharacterSet characterSetWithCharactersInString:#";\r"];
// get content from url
NSString* urlContent = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://192.168.1.10:92/get_camera_params.cgi"] encoding:NSUTF8StringEncoding error:nil];
// split content into rows
NSArray* lines = [urlContent componentsSeparatedByString:#"\n"];
for(NSString* line in lines)
{
//split row
NSArray* comps = [line componentsSeparatedByString:#"="];
if(comps.count < 2)
continue;
// [comp objectAtIndex:0] is the value left of =
// [comp objectAtIndex:1] is the value right of =
// left string without the 'var '
NSString* varName = [[comps objectAtIndex:0] stringByReplacingOccurrencesOfString:#"var " withString:#""];
// right string with trimming the ';'
int varValue = [[[comps objectAtIndex:1] stringByTrimmingCharactersInSet:charSetToReplace] intValue];
// write into dictionary
[dict setObject:[NSString stringWithFormat:#"%d",varValue] forKey:varName];
}
// as int
int myResolution = [[dict objectForKey:#"resolution"] intValue];
int myBrightness = [[dict objectForKey:#"brightness"] intValue];
// or as String
NSString* myResolutionStr = [dict objectForKey:#"resolution"];
NSString* myBrightnessStr = [dict objectForKey:#"brightness"];
// and so on ...

How to append NSMutable strings into a UILabel

This is my first question to Stack Overflow. I have been using this site for a while and have used it's resources to figure out answers to my programming questions but I'm afraid I can't find the answer I'm looking for this time.
I've created these five strings:
//List five items from the book and turn them into strings
//1 Josh the Trucker
NSString *stringJosh = #"Josh the Trucker";
//2 The Witch from the Remote Town
NSString *stringWitch = #"The Witch from the Remote Town";
//3 Accepting the curse rules "Willingly and Knowingly"
NSString *stringRules = #"Accepting the curse rules, --Willingly and Knowingly--";
//4 Josh's time left to live--Five Days Alive Permitted
NSString *stringFiveDays = #"Josh's time left to live--Five Days Alive Permitted";
//5 The Fire Demon Elelmental
NSString *stringDemon = #"The Fire Demon Elelmental";
Then, I've put them in an array:
//Create an array of five items from the book
NSArray *itemsArray = [[NSArray alloc] initWithObjects:
stringJosh,
stringWitch,
stringRules,
stringFiveDays,
stringDemon,
nil];
Then, I created this mutable string where I need to loop through the array and append the items to a UIlabel.
NSMutableString *itemsString = [[NSMutableString alloc] initWithString:
#"itemsArray"];
Here's the loop, which displays the items in the console log.
for (int i=0; i<5; i++)
{
NSLog(#"Book Item %d=%#", i, itemsArray[i]);
}
My question is, how do I append these items into the UIlabel?
These functions are in my appledelegate.
In my viewDidAppear function (flipsideViewController) I have:
label8.text =""----thats where the looped info needs to go.
How do I do this?
I feel I need to put them together and append where the NSLog should be...but how do I transfer that info to the textlabel?
I hope I explained myself.
We haven't done ANY append examples, I guess this is where I need to get answers from the "wild"
This is the wildest coding environment I know so I'm hoping I can find some direction here.
Thanks for taking a look!
Once you have all your strings that you want to concatenate in NSArray you can combine them with single call (with whatever separator you want):
NSString *combinedString = [itemsArray componentsJoinedByString:#" "];
If you need more complex logic you can use NSMutableString to create result you want while iterating array, i.e.:
NSMutableString *combinedString = [NSMutableString string];
[itemsArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
[combinedString appendFormat:#"Book Item %d=%# ", idx, obj];
}];
Note also that it is better to iterate through collections using fast enumeration or block enumeration rather than using plain index-based for loop.
NSMutableString *labelText = [NSMutableString string];
int i = 0;
for (NSString *item in itemsArray)
[labelText appendFormat:#"Book Item %d=%#\n", i++, item];
label8.text = labelText;
DO this
UILabel *mainlabel;
mainlabel.text = [origText stringByAppendingString:get];
Add your text to mainlabel.. orig text is mutable string or else in forloop just append array object at index text to label.put above line of code in forloop

Create string based on characters expected

I would like to create a string based on the number of characters passed in. Each character passed in will be a "X". So for example, if the length passed in is 5, then the string created should be
NSString *testString=#"XXXXX";
if it is 2 then it would be
NSString *testString=#"XX";
Can anyone tell me what the most efficient way to do this would be?
Thank you!
If you know the maximum length is some reasonable number then you could do something simple like this:
- (NSString *)xString:(NSUInteger)length {
static NSString *xs = #"XXXXXXXXXXXXXXXXXXXXXXXXXXX";
return [xs substringToIndex:length];
}
NSString *str = [self xString:5]; // str will be #"XXXXX";
If you pass in too large of a length, the app will crash - add more Xs to xs.
This approach is more efficient than building up an NSMutableString but it does make an assumption about the maximum length you might need.
- (NSString *)stringOf:(NSString *)str times:(NSInteger)count
{
NSMutableString *targ = [[NSMutableString alloc] initWithCapacity:count];
for (int i=0; i < count; i++)
{
[targ appendString:str];
}
return targ;
}
and
[self stringOf:#"X" times:4];
note that initWithCapacity: (in performance manner) better than init. But I guess that's all for efficiency.
The way I would do it is
NSMutableString *xString = [[NSMutableString alloc] init];
while ( int i = 0; i < testString.length; i++ ) {
[xString appendString:#"X"];
i++;
}
NSUInteger aLength. // assume this is the argument
NSMutableString *xStr = [NSMutableString stringWithCapacity: aLength];
for ( NSUInteger i = 0; i < aLength; i++ ) {
[xStr appendFormat:#"X"];
}
The following will do what you ask in one call:
NSString *result = [#"" stringByPaddingToLength:numberOfCharsWanted
withString:characterToRepeat
startingAtIndex:0];
where numberOfCharsWanted is an NSUInteger and characterToRepeat is an NSString containing the character.

Resources