Printing from NSMutableArray - ios

So i want to print the users in an NSMutableArray. But the strings keep coming out as nil.
here is what i have:
int users = 0;
- (IBAction)addNewUser:(id)sender {
NSString *string;
string = userNameTextField.text;
[usernameArray insertObject:string atIndex:users];
users++;
[self showUsers];
}
-(void)showUsers{
for (int i = 0; i < users; i++){
NSString *s = textView.text;
NSString *add;
add = [NSString stringWithFormat:#"%# ",[usernameArray objectAtIndex:i]];
NSString *display = [NSString stringWithFormat:#"%# \n %#", s, add];
textView.text = display;
}
}
i have also tried
-(void)showUsers{
for (int i = 1; i < users; i++){
NSString *s = textView.text;
NSString *add;
add = [usernameArray objectAtIndex:i];
NSString *display = [NSString stringWithFormat:#"%# \n %#", s, add];
textView.text = display;
}
}

First of all try using more comprehensive names for the objects. I'm rewriting your code.
Common Causes for the problem : Array not initialized, you are starting your for cycle with int i equal to 1, so you are missing the object at index 0 at your mutable array. Try the following code.
#interface InterfaceName : InterfaceInherits <IfDelegate> {
int usersCount;
NSMutableArray * usernameArray;
}
#implementation InterfaceName
/*There's no more confident way to initialize a variable than in the init method of the class. */
-(id)init{
usersCount = 0;
//You have to be sure that your array is not nil
usernameArray = [NSMutableArray alloc]init]];
return self;
}
- (IBAction)addNewUser:(id)sender {
NSString *username = [usernameTextField text];
[usernameArray insertObject:username atIndex:usersCount];
usersCount++;
//I'll omit the display as I'm not sure what you were doing with it.
}
-(void)showUsers{
for (int i = 0; i < usersCount; i++){
NSString *retrievedUser = [usernameArray objectAtIndex:i];
NSString *display = [NSString stringWithFormat:#"User Retrieved : %#",retrievedUser];
textView.text = display;
}
}
#end

Related

How to reference an array from another function Objective-C

I have declared array in SomeClass.h It's a global variable isn't it?
#property (nonnull, nonatomic, retain) NSMutableArray *additional_tabs;
Below I declared 2 function where I use this array.
- (id _Nullable)initFromJSON:(NSDictionary *_Nullable)dictionary;
- (void)moreTabs:(NSMutableArray *_Nullable)a;
Below is if-statement I used inside initFromJSON function.
if ([Tools isNonullValueForKey:[dictionary valueForKey:#"additional_tabs"]]) {
_additional_tabs = [NSMutableArray new]; //really I need them?
_additional_tabs = [dictionary valueForKey:#"additional_tabs"];
NSLog(#"additionalTabCount (initJSON) = %lu", [_additional_tabs count]);
for (int i = 0; i < [_additional_tabs count]; i++) {
if ([Tools isNonullValueForKey:[_additional_tabs valueForKey:#"_id"]]) {
_additional_tab_id = [[_additional_tabs valueForKey:#"_id"] objectAtIndex:i];
}
if ([Tools isNonullValueForKey:[_additional_tabs valueForKey:#"names"]]) {
NSDictionary *dic = [[_additional_tabs valueForKey:#"names"] objectAtIndex:i];
_en_additional_tab_name = [dic valueForKey:#"en"];
_pl_additional_tab_name = [dic valueForKey:#"pl"];
}
if ([Tools isNonullValueForKey:[_additional_tabs valueForKey:#"url"]]) {
_additional_tab_url = [[_additional_tabs valueForKey:#"url"] objectAtIndex:i];
}
NSLog(#"%# %d %# %# %# %#", #"pos", i, #"id: ", _additional_tab_id, #"url: ", _additional_tab_url);
}
}
And this [_additional_tabs count] have 17.
But in function moreTabs:
NSLog(#"additional tabs count: %lu",[_additional_tabs count]);
for (int i = 1; i < [_additional_tabs count]; i++) {
[a addObject:[[VCTab alloc] initWithIdAndTypeAndUrl:[[_additional_tabs valueForKey:#"_id"] objectAtIndex:i] :VCTabAdditional :[[_additional_tabs valueForKey:#"url"] objectAtIndex:i]]];
}
}
return [_additional_tabs count] with nil... look like is different array or cleared?
I would be very grateful for your help :)
All the best

NSString from NSData is incomplete

When I use [[NSString alloc] initWithData:subdata encoding:encoding] method , I find the string is incomplete. Why? Any restrictions in NSString?
Then,I suspect that the data is too large,so I create a new method to Transfer.
-(NSString *)stringFromData:(NSData *)data encoding:(NSStringEncoding)encoding{
NSInteger DataLen = data.length;
NSInteger segLen = 5000;
NSInteger times = DataLen/segLen;
NSInteger fristLen = DataLen%segLen;
NSMutableString *str = [NSMutableString string];
[str appendString:[[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, fristLen)] encoding:encoding]];
NSLog(#"%#",str);
while (times--) {
NSData *subdata = [data subdataWithRange:NSMakeRange(fristLen, segLen)] ;
if (subdata) {
NSString*substr = [[NSString alloc] initWithData:subdata encoding:encoding]; //tag1
NSLog(#"%#",substr);
if (substr) {
[str appendString:substr];
}
fristLen += segLen;
}else{
break;
}
}
return str;
}
but in tag1, I find the string is null in some conditions. What is the problem?

iOS: Reorder NSString characters alphabetically [duplicate]

I'm trying to re-arrange words into alphabetical order. For example, tomato would become amoott, or stack would become ackst.
I've found some methods to do this in C with char arrays, but I'm having issues getting that to work within the confines of the NSString object.
Is there an easier way to do it within the NSString object itself?
You could store each of the string's characters into an NSArray of NSNumber objects and then sort that. Seems a bit expensive, so I would perhaps just use qsort() instead.
Here it's provided as an Objective-C category (untested):
NSString+SortExtension.h:
#import <Foundation/Foundation.h>
#interface NSString (SortExtension)
- (NSString *)sorted;
#end
NSString+SortExtension.m:
#import "NSString+SortExtension.h"
#implementation NSString (SortExtension)
- (NSString *)sorted
{
// init
NSUInteger length = [self length];
unichar *chars = (unichar *)malloc(sizeof(unichar) * length);
// extract
[self getCharacters:chars range:NSMakeRange(0, length)];
// sort (for western alphabets only)
qsort_b(chars, length, sizeof(unichar), ^(const void *l, const void *r) {
unichar left = *(unichar *)l;
unichar right = *(unichar *)r;
return (int)(left - right);
});
// recreate
NSString *sorted = [NSString stringWithCharacters:chars length:length];
// clean-up
free(chars);
return sorted;
}
#end
I think separate the string to an array of string(each string in the array contains only one char from the original string). Then sort the array will be OK. This is not efficient but is enough when the string is not very long. I've tested the code.
NSString *str = #"stack";
NSMutableArray *charArray = [NSMutableArray arrayWithCapacity:str.length];
for (int i=0; i<str.length; ++i) {
NSString *charStr = [str substringWithRange:NSMakeRange(i, 1)];
[charArray addObject:charStr];
}
NSString *sortedStr = [[charArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] componentsJoinedByString:#""];
// --------- Function To Make an Array from String
NSArray *makeArrayFromString(NSString *my_string) {
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i = 0; i < my_string.length; i ++) {
[array addObject:[NSString stringWithFormat:#"%c", [my_string characterAtIndex:i]]];
}
return array;
}
// --------- Function To Sort Array
NSArray *sortArrayAlphabetically(NSArray *my_array) {
my_array= [my_array sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
return my_array;
}
// --------- Function Combine Array To Single String
NSString *combineArrayIntoString(NSArray *my_array) {
NSString * combinedString = [[my_array valueForKey:#"description"] componentsJoinedByString:#""];
return combinedString;
}
// Now you can call the functions as in below where string_to_arrange is your string
NSArray *blowUpArray;
blowUpArray = makeArrayFromString(string_to_arrange);
blowUpArray = sortArrayAlphabetically(blowUpArray);
NSString *arrayToString= combineArrayIntoString(blowUpArray);
NSLog(#"arranged string = %#",arrayToString);
Just another example using NSMutableString and sortUsingComparator:
NSMutableString *mutableString = [[NSMutableString alloc] initWithString:#"tomat"];
[mutableString appendString:#"o"];
NSLog(#"Orignal string: %#", mutableString);
NSMutableArray *charArray = [NSMutableArray array];
for (int i = 0; i < mutableString.length; ++i) {
[charArray addObject:[NSNumber numberWithChar:[mutableString characterAtIndex:i]]];
}
[charArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
if ([obj1 charValue] < [obj2 charValue]) return NSOrderedAscending;
return NSOrderedDescending;
}];
[mutableString setString:#""];
for (int i = 0; i < charArray.count; ++i) {
[mutableString appendFormat:#"%c", [charArray[i] charValue]];
}
NSLog(#"Sorted string: %#", mutableString);
Output:
Orignal string: tomato
Sorted string: amoott

NSMutableArray have restriction in adding object?

I am using NSMutableArray for adding objects.But its add only first 10 objects.
I have code for sharing
for (int j = 0; j<[feedData count]; j++)
{
[sharingItems addObject:[self whatsappdata:[feedData objectAtIndex:j]]];
}
This method return NSString type text.
Please provide me valid solution for this.
Thanks in Advance
-(NSString *)whatsappdata:(NSDictionary *)cellData1
{
NSString *brandName = [NSString stringWithFormat:#"%#", [cellData1 objectForKey:#"brand_name"]];
NSString *modelName = [NSString stringWithFormat:#"%#", [cellData1 objectForKey:#"brand_model_name"]];
NSString *version = [NSString stringWithFormat:#"%#", [cellData1 objectForKey:#"version_name"]];
if ([version isEqualToString: #"<null>"])
{
version = #"";
}
NSString *year = [NSString stringWithFormat:#"%#", [cellData1 objectForKey:#"model_year"]];
if (year == nil || [year isEqualToString:#"0"])
{
year = #"";
}
NSString *inventoryValue = [NSString stringWithFormat:#"%#",[cellData1 objectForKey:#"inventory_type"]];
NSInteger value = [inventoryValue intValue];
NSString *inventoryName;
NSString *msg;
if(value == 1)
{
inventoryName = [NSString stringWithFormat:#"%#", #"Stock"];
i++;
NSString *text2 = [NSString stringWithFormat:#"%d.%# %# %#- %# Single Owner\n",i, brandName, modelName, version, year];
msg = [NSString stringWithFormat:#"%#",text2];
msg= [msg stringByReplacingOccurrencesOfString:#"\n" withString:#"<br/>"];
}
else
{
inventoryName = [NSString stringWithFormat:#"%#", #"Required"];
msg = #"";
}
return msg;
//end data
}
Most probably "fetch limit" has set for 'NSFetchRequest' inside your code.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setFetchLimit:10];//such code you need to find and remove/change fetch limit
you need to allocate memory to array before adding elements
sharingItems = [[NSMutableArray alloc]init];

NSString subsstring

I have a string like this
12,23,45,3,12,
What I want to do is get this each number and check with an array value. How I can get each value as a substring to check
Thanks
Break this string to array.
NSString *string = #"12,23,45,3,12,";
NSArray *array = [string componentsSeparatedByString:#","];
Then you can compare with the array.
EDIT :
As per your comment that you want to check all the string values to be present in main-other-array.
NSString *string = #"12,23,45,3,12";
NSArray *array = [string componentsSeparatedByString:#","];
//below is the main-other-array
NSArray *toCheckArray = #[#"124",#"23",#"45",#"3",#"12",#"1000"];
BOOL arrayIsContainedInToCheckArray = YES;
for (NSString *arrayObj in array) {
if (![toCheckArray containsObject:arrayObj]) {
arrayIsContainedInToCheckArray = NO;
}
}
NSLog(#"%#",arrayIsContainedInToCheckArray?#"All exist":#"All doesn't exist");
May be it helps you :
NSString *str = #"12,23,45,3,12";
NSArray *strArray = [str componentsSeparatedByString:#","];
NSArray * anotherArray = nil; // have some value
for (NSString * value in strArray)
{
int intVal = [value integerValue]; // here is your separate value
for (int i = 0; i < [anotherArray count]; i++) // You can check against another array
{
id anotherVal = [anotherArray objectAtIndex:i];
// Here you can check intVal and anotherVal from another array
}
}
Use this, It will help you..
NSArray *detailArray = [yourString componentsSeparatedByString:#","];

Resources