Remove objects from an array before calling the API - ios

I'm creating a table view which is hooked to an API. However, I'm having trouble with doing a refresh on pull. I've added the logic, however I can't seem to delete all the objects in the array before making a new api call.
Here is my array
var recentArray = Array<News>()
UIRefreshControl function:
func refresh(sender: UIRefreshControl){
lastObjectIndex=0
// remove all objects
getRecent()
self.tableVIew.reloadData()
self.refreshControl?.endRefreshing()
}
How can i remove all objects in my array before calling getRecent, which adds an object to the array?

You can reset your array like this:
recentArray = []
The compiler already knows the type of the array objects, so there's no need to do anything else.

You can remove all objects by calling
recentArray.removeAll(keepCapacity: false)

You can removed all object by adding following code befor getRecent called.
var array = [0, 1, 2, 3]
array.removeAll()
let count = array.count
// count is 0
Hope this will help you.

Related

Add last element to an array from for loop

I have a code like so...
for element in self.arr_Offline {
self.arr_OfflineTemp.add(element)
break
}
self.arr_Offline.removeObject(at: 0)
Here I'm looping through an array called self.arr_Offline, adding the first element from that array into another array called self.arr_OfflineTemp and immediately doing break so that the second array will have just one element and then once I'm outside the for-loop, I remove the added object from the main array by doing self.arr_Offline.removeObject(at: 0)
But I want to add the last element to self.arr_OfflineTemp instead of the first and then remove that last element from self.arr_Offline. It should look something like so...
for element in self.arr_Offline { // looping through array
self.arr_OfflineTemp.add(lastElementOf'self.arr_Offline') //add last element
break
}
self.arr_Offline.removeObject(at: 'last') //remove that last element that was added to `arr_OfflineTemp`
How can I achieve this..?
First of all never use NS(Mutable)Array and NS(Mutable)Dictionary in Swift.
Native Swift Array has a convenient way to do that without a loop
First element:
if !arr_Offline.isEmpty { // the check is necessary to avoid a crash
let removedElement = self.arr_Offline.removeFirst()
self.arr_OfflineTemp.append(removedElement)
}
Last element:
if !arr_Offline.isEmpty {
let removedElement = self.arr_Offline.removeLast()
self.arr_OfflineTemp.append(removedElement)
}
And please drop the unswifty snake_case names in favor of camelCase
Did you try the same approach with reversed() Swift:
for i in arr.reversed():
// your code logic
After adding element, you can remove the last element from the list using this:
lst.popLast() or lst.removeLast()
Try this for the above code:
for element in self.arr_Offline.reversed() {
self.arr_OfflineTemp.add(element)
break
}
self.arr_Offline.popLast()
Is this something you are looking for?

Is my array empty or not?

I have an array that becomes loaded with objects when I call it in my viewDidLoad method. I know that it is not empty because I am able to print the data and the count of the array when I call it in viewDidLoad.
However, when I try to take the data out of the array and put it into a text view, the array appears to be empty. The code below is where I attempt to add the items from requestList2 into a textfield in tableView:cellForRowAtIndexPath:.
Why does does my array possess data when I call it in viewDidLoad, but not when I try to add it to cell.usernameOfRequestSender.text?
if (requestList2.count > 0){
var user = requestList2.objectAtIndex(indexPath.row) as! String
cell.usernameOfRequestSender.text = user
}
return cell

SWIFT: "removeAtIndex" don't work with (sender:UIButton)

#IBOutlet var items: [UIButton]
#IBAction func itemsHidden(sender: UIButton) {
sender.hidden = true
items.removeAtIndex(sender)
}
Hello.
For example, i have array of items.
The code has the error: "Cannot invoke 'removeAtIndex' with an argument list of type (UIButton)".
What i need to do, that "removeAtIndex" works?
Thanks...
A removeAtIndex method expects to get an index as a parameter.
If you want to remove an object use func removeObject(_ anObject: AnyObject)
EDIT
There's no removeObject in a swift's array (only in NSMutableArray).
In order to remove an element, you need to figure out it's index first:
if let index = find(items, sender) {
items.removeAtIndex(index)
}
You don't tell us the class of your items object.
I assume it's an Array. If not, please let us know.
As Artem points out in his answer, removeAtIndex takes an integer index and remove the object at that index. The index must be between zero and array.count-1
There is no removeObject(:) method for Swift Array objects because Arrays can contain the same entry at more than one index. You could use the NSArray method indexOfObject(:) to find the index of the first instance of your object, and then removeAtIndex.
If you're using Swift 2, you could use the indexOf(:) method, passing in a closure to detect the same object:
//First look for first occurrence of the button in the array.
//Use === to match the same object, since UIButton is not comparable
let indexOfButton = items.indexOf{$0 === sender}
//Use optional binding to unwrap the optional indexOfButton
if let indexOfButton = indexOfButton
{
items.removeAtIndex(indexOfButton)
}
else
{
print("The button was not in the array 'items'.");
}
(I'm still getting used to reading Swift function definitions that include optionals and reference protocols like Generator so the syntax of the above may not be perfect.)

iOS: remove objects or reinitialize arrays in swift?

I'm new in swift and I want to know if the beast approach to reuse an array is to delete all object inside or reinitialize it.
For example if I have:
var my_array:NSMutableArray! //global variable
and the first method that I use:
func firstMethod{
my_array = NSMutableArray()
my_array.addObject("one")
my_array.addObject("two")
my_array.addObject("three")
...
}
for example now in another method I need my_array empty:
the best solution is this:
func newmethod() {
my_array = NSMutableArray() //reinitialize (drastic method)
//here, all new operation with my_array
}
or is this?:
func newmethod() {
if my_array == nil{
my_array = NSMutableArray()
} else {
my_array.removeAllObjects()
}
}
The general answer is it depends. There is a really major danger when it comes to having mutable public properties, particularly when it comes to multithreaded apps.
If you always reinitialize, it is more likely that you're safe from multithreading issues.
If you are emptying the array, you are prone multithreading issues. You're probably going to get index out of bounds crashes and the like when you are emptying the array on one thread and trying to access any index on another thread.
Thread A check's the array's count. It's 10. Thread B empties the
array. Array's count is now 0. Thread A tries to access an object at
index 3. Crash.
Even though your code looks fine, something like this:
if array.count > 3 {
array[3].doThings()
}
Multithreading means that another thread mutating the array between that code checking the count and that code accessing an index.
I would opt for immutable objects as much as possible, and I would avoid mutating mutable objects that have any chance of being accessed in a thread unsafe manner.
Why you are reinitializing the array there is no need to reinitialize it.And if you reinitialize then it will point to another memory address so it would be better to reuse without reinitialize. You can do like this
if (my_array == nil){
my_array = NSMutableArray();
}
else{
//my_array.removeAllObjects();
// Do your stuff here
}

Creating and populating an empty Array

I'm actually learning swift in order to develop iOS apps. I'd like, as an exercise, to create and populate an empty array, that would be filled by using a textfield and a button on the storyboard.
var arr = []
// When button is pressed :
arr.append(textfield.text)
XCode tells me that the append method is not a method of NSArray. So I have used the addObject one, but it is still not correct as the arr variable contains nil.
So here are my three questions :
Is it possible to create an empty array, and if so, how to populate it ?
Sometimes, in my ViewController, when I create a non-empty array, the append method is apparently not valid, and I don't understand why..
Finally, why even though I use the syntax :
var arr = [1] // For example
The arr object is NSArray object and not a NSMutableArray object, making it impossible to add/remove any object that is contained in it?
I hope my questions are clear, if not I'll upload more code of what I'm trying to build,
thank you for your answers !
Try to define your array as a String array, like this:
var arr: [String] = []
And then append to your list, either by:
arr.append("the string")
or
arr += ["the string"]
Empty array can be created using the following syntax.
var emptyArray = [String]()
emptyArray.append("Hi")
see this
You can use following also to add elements to your array.
//append - to add only one element
emptyArray.append("Hi")
//To add multiple elements
emptyArray += ["Hello", "How r u"]
emptyArray.extend(["am fine", "How r u"])
//Insert at specific index
emptyArray.insert("Who r u", atIndex: 1)
//To insert another array objects
var array1 = ["who", "what", "why"]
emptyArray.splice(array1, atIndex: 1)

Resources