i need to hv an array of 20 objects.
initially array will hv 0 objects.
i hv add objbects 1 by 1,till it gets filled with 20 objects.
As soon as array gets 20 objects,and i try to insert a new object(for ex 21st object)
it should delete the 20th object and add itself to first position.
i hope i m giving u a clear picture,about wat i am looking for.
hope for a quick reply
regards
shishir
You could create your own class that uses an NSMutableArray for storage. When adding an item, first check whether there are already 20 objects in the array. If there are, remove the last object from the array. Then add the new object at the front.
- (void)addObject:(id)anObject
{
if ([dataArray count] == 20) {
[dataArray removeLastObject];
}
[dataArray insertObject:anObject atIndex:0];
}
The above will always add the newest object at the front of the array. I guess that is what you want.
Related
I have an array of objects. Each object has property "date" and "title".
I want to populate sectioned UITableView with those items like:
Section 1 - 2012.06.12 (taken from object.date)
Cell 1.1: Title 1 (taken from object.name)
Cell 1.2: Title 2
Cell 1.3: Title 3
...
Section 2 - 2012.06.13
Cell 2.1: Title 1
Cell 2.2: Title 2
..
Section 3 ..
I can do that by manually creating 1..n NSMutableArrays for all date combinations and filling them with object.name values. But the problem is I do not know how many date combinations there are, so it should be done dynamically. Also, the date property can repeat in different objects
My object structure is:
Object
-NSDate - date
-NSString - title
UPD:
I was thinking if it is possible to create NSDictionary, where the key would be my date and the object would be NSArray, which contains all my items for the key-date. But I do not know how to do that dynamically.
I hope I explained my question clearly enough.
Thank you in advance!
You can create arrays based on date.You have array of objects, so iterate through this array of objects to get distinct dates, as follows:
for(int i =0;i<[objectsArr count];i++)
{
if(![newDateArr containsObject:[objectsArr objectAtIndex:i].date])
{
[newDateArr addObject:[objectsArr objectAtIndex:i].date];
}
NSMutableArray *newTitleArray = [newTitleDictionary objectForKey:#"[objectsArr objectAtIndex:i].date"];
if(newTitleArray != nil)
{
[newTitleArray addObject:[objectsArr objectAtIndex:i].title];
}
else
{
newTitleArray = [[[NSMutableArray alloc] init] autorelease];
[newTitleArray addObject:[objectsArr objectAtIndex:i].title];
}
[newTitleDictionary setValue:newTitleArray forKey:#"[objectsArr objectAtIndex:i].date"];
}
where newTitleDictionary and newDateArr are declare outside this method.Now you can use both is newTitleDictionary and newDateArr to populate tableview.
If I understand you correctly, you want to put an object into an array and then use that array to populate a table view?
Just add the date object each time to the NSMutableArray.
[myArray addObject:dateObject];
Then when it comes to populating the table view..
DateObject *newDateObj = [myArray objectAtIndex:index];
I hope this helps and I understood your question
EDIT To answer now I understand a bit more.
Step 1
Check through the existing array of dates and see if there are any that match maybe by iterating through it using a for loop. Search online for how to compare NSDate.
Step 2 If it doesn't match any then insert it into the array as an array with just that date on it's own so the array count will be one. If it does match then insert it into the array along with that one making the array count 2 or more.
Step 3 When it comes to declaring the section amount for the table just return the dateHolderArray count.
Step 4 When declaring the amount of rows in each section, return the array count for the array thats inside the dateHolderArray.
Step 5 Display the content when it comes to populating the cells with information. It becomes just a task of getting the dates from the arrays using the section ids and row ids.
This is how I would do it, there are probably many other methods. Any questions just ask
I am trying to remove objects at array starting at index 5 to the end of the list. I have a for loop to do this, however now I discovered
- (void)removeObject:(id)anObject inRange:(NSRange)aRange
The question is what is the anObject here? I only need range as far as I know
removeObject:inRange: deletes an object within a certain range. This method would be useful if you wanted delete the string #"Hello World" only if it is one of the first 5 elements.
It sounds like what you are trying to do is delete all objects after the 5th element. If that is what you are trying to do, you should use the removeObjectsInRange: method. For example:
NSRange r;
r.location = 5;
r.length = [someArray count]-5;
[someArray removeObjectsInRange:r];
You want
- (void)removeObjectsInRange:(NSRange)aRange
Removes from the array each of the objects within a given range.
I'm adding an object to a NSMutableArray like this:
[array addObject:myObject];
I now want to send a reference to my delegates of the Array Index where this object was added.
Is there an easy way to find out the index where my object was added in the array so that later I can call
[array objectAtIndex:index]
to get a reference back for it?
Thanks!
Rather than passing the index of an object (which could be incorrect) to your delegate, pass a reference to the object itself. If the delegate needs the index of the object in the array, it can figure it out itself using -indexOfObject: as Antonio MG describes. The index of any given object in a mutable array can change as objects are added, inserted, and deleted. Counting on indices to remain valid over any period of time is like leaving a jelly sandwich on the counter -- it's sure to attract bugs.
You need to serialize access to a mutable array and -addObject: always adds the object to the end of the array. Given those two assertions, you know the index of the next added object will always be the current length of the array. So the following will hold true:
NSUInteger nextIndex = [array count];
[array addObject:myObject];
// you can now tell your delegates that nextIndex is the index of myObject
Use this method for that:
index = [animalOptions indexOfObject:myObject];
The latest added object should be at [array count] - 1 index. You can always rely on "count - 1" scheme to determine the last index.
If you call addObject you always add the object at the end (so count - 1).
You can use "insertObject:atIndex:" to specify an index.
For your question: indexOfObject:
Direct after adding the object's index is array.count -1 .
i am displaying array of elements in a tableview.
Now i need to display some other new elements on table view.
For this i try by adding new elements to array which is datasource of table view and reloading the table.
Then It displaying the newly added elements but the problem is it is adding at last element of array so it displaying at the bottom of the table view.
But i need to display that new value at the top of the table view.
How can i done this can any one please help me.
Thank u in advance.
(Let me add comment if any one does n't get my question).
Insert the new items at the top of your array using NSMutableArray insertObject: atIndex:.
Create a new array with a capacity of the old array + n new objects. Add the new objects, then loop through the previous array and copy that into the new array. This way the first index - n-1 will have the items you added, therefore being displayed at the top of the table.
There may be an easier way to do this, but this implementation will definitely work.
Do you use arrayByAddingObjectsFromArray: to add new elements?
If so, the objects are added to the end of the original array, and thus displayed at the end of the table view.
So instead of adding new array to the end of the old array, how about adding old array to the end of the new array?
self.arrayForTable = [arrayWithNewElements arrayByAddingObjectsFromArray:arrayForTable];
If you are using NSMutableArray so there are many function available for inserting the new element at your desire place in array and they are ....
Inserts a given object into the array's contents at a given index.
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index
Inserts the objects in in a given array into the receiving array at the specified indexes.
- (void)insertObjects:(NSArray *)objects atIndexes:(NSIndexSet *)indexes
Below is the code from Apple Documentation ...
NSMutableArray *array = [NSMutableArray arrayWithObjects: #"one", #"two", #"three", #"four", nil];
NSArray *newAdditions = [NSArray arrayWithObjects: #"a", #"b", nil];
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:3];
[array insertObjects:newAdditions atIndexes:indexes];
NSLog(#"array: %#", array);
// Output: array: (one, a, two, b, three, four)
In the use case where you have an array of entities that need to be populated at that beginning of your existing data source, try the following:
-(NSMutableArray*)returnReorganizedArrayWithEarlierEntities:(NSArray*)theEarlierEntities{
theEarlierEntities = [[theEarlierEntities reverseObjectEnumerator] allObjects];
for(int i = 0; i < [theEarlierEntities count]; i++)
[dataSourceArray insertObject:[theEarlierEntities objectAtIndex:i] atIndex:0];
return dataSourceArray;
}
What this method does is reverse the order of the new entities you want added so that they are placed correctly (bottom-up) at the beginning of your existing data structure.
Cheers!
If you still want to use Array you can do this:
imagine we have an array whose type is your model(struct to class).
var yourArray = [YourModel]()
to add a new element on top of the array you can use
yourArray.insert(newElemet: Model, at: 0)
refer to this thread: Add an element to an array in Swift
My aim is to produce an array, which I can use to add section headers for a UITableView. I think the easiest way to do this, is to produce a sections array.
I want to create section headers for dates, where I'll have several or no rows for each.
So in my populate data array function, I want to populate a display array. So record 1, look for the first date in my display array, create a new array item if it doesn't exist, if it does exist add 1 to the count.
So I should end up with something like this.
arrDisplay(0).description = 1/June/2001; arrDisplay(0).value = 3;
arrDisplay(1).description = 2/June/2001; arrDisplay(1).value = 0;
arrDisplay(2).description = 3/June/2001; arrDisplay(2).value = 1;
arrDisplay(3).description = 5/June/2001; arrDisplay(3).value = 6;
My question is how do I create and use such an array with values, where I can add new elements of add to the count of existing elements and search for existing elements ?
I think, if i understand you, an NSMutableDictionary would work. (as NR4TR said) but, i think the object would be the description and the key would be the count. you could check for the key and get the count in the same gesture. if the return value of objectForKey is nil, it doesn't exist.
NSMutableDictionary *tableDictionary = [[NSMutableDictionary alloc] init];
NSString *displayKey = #"1/June/2001";
NSNumber *displayCount = [tableDictionary objectForKey:displayKey];
if (displayCount != nil) {
NSNumber *incrementedCount = [[NSNumber alloc] initWithInteger:[displayCount integerValue] + 1];
[tableDictionary removeObjectForKey:displayKey];
[tableDictionary setValue:incrementedCount
forKey:displayKey];
[incrementedCount release];
}
else {
NSNumber *initialCount = [[NSNumber alloc] initWithInteger:1];
[tableDictionary setValue:initialCount
forKey:displayKey];
[initialCount release];
}
EDIT: Hopefully this isn't pedantic, but I think a couple pointers will help.
Dictionaries, Sets, and Arrays all hold objects for retrieval. The manner of holding and retrieval desired drives the decision. I think of it based on the question 'what is the nature of the information that I have when I need an object being held?'
NSDictionary and NSMutableDictionary
Hold n objects per key. (I think...I haven't had to test a limit, but i know you can get an NSSet back as a value.)
KEY is more important than INDEX. I don't think of dictionaries as ordered. they know something and you need to ask the correct question.
NSArray and NSMutableArray
hold n objects in order.
INDEX is most important bit of information. (you can ask for the index of an object but, even here, the index is the important part)
you will typically drive table views with an array because the ordered nature of the array fits.
NSSet, NSMutableSet, and NSCountedSet
A collection of objects without order.
You can change any of these into the other with something like [nsset setFromArray:myArray];
and all of these things can hold the other as objects. I think an array as your top level is the correct thinking, but beyond that, it becomes an issue of implementation
Try array of dictionaries. Each dictionary contains two objects - section title and array of section rows.
If you want to have a description AND a rowcount then you can either create a class with those two properties and generate an NSArray of objects with that class or instead of all that you can just use an NSDictionary to store key/value lookups.
I think NSCountedSet is closest to what you want. It doesn't have an intrinsic order, but you can get an array out of it by providing a sort order.