I have a array of object of custom class. My class is Person. So i want to check if arrPerson contains an object then it should not be added again in array.
Here is my code
for value in data {
if self.arrPerson.contains(where: {($0.id != value.id)}){
self.arrPerson.append(value)
}
}
Please tell me how can i check if object of custom class already added then it should not be added again
if !self.arrPerson.contains(where: {($0.id == value.id)}){
self.arrPerson.append(value)
}
You can use "set" instead of array it will avoid the duplicate values.
Related
I have a NSManagedObject class with two relationships: courseAand courseB.
These relationships should be represented in a dynamic variable. How is it possible to change this variable from outside the class?
#objc(Universtity)
public class Universtity: NSManagedObject {
dynamic var name: String {
get {
let name = self.courseA?.name
return name!
}
}
}
For example from within a ViewController like University.name = University.courseB.name ?
I was thinking about a Notifikation, but this seems maybe a little more complicated as it could be.
And if there is no other way, how should I implement the observer inside the University class?
Thank you for every idea.
Looking at your code, you have declared a "computed" or "ready-only" variable. This is a variable whose value comes from another variable or combination of variables.
I can't see your data model, so it's not clear if you have defined a name parameter in the Core Data model. Regardless, if you have the logic is somewhat confused, because the getter you have defined means any value it may hold would be ignored anyway. You would need to define a setter to set self.courseA.name if you want to ensure the value can be written to. You don't need to worry about key-value coding notifications, because they will be triggered by the Core Data Managed Object.
public class Universtity: NSManagedObject {
dynamic var name: String {
get {
let name = self.courseA?.name
return name!
}
set(newValue) {
courseA!.name = newValue
}
}
}
Also the pattern you have used to force unwrap a non-optional value in your getter isn't optimal. I haven't edited this because that is another discussion, but I would suggest asking yourself the question am I sure why I am doing this? for every "?" and "!" you use.
I have an array of view model. Now I want to check that view model array to contain a word within an array.
public IQueryable<CategorisedPostViewModel> GetRelatedPostbyCategories(string categories)
{
var ctries = categories.Split(',');
var result = GetAllCategoriedPost().**Where(p=>p.CategoryName.Contains(ctries)).**OrderByDescending(c => c.Published);
return result;
}
How can I search that bold portions without loop?
We may assume for simplicity,
p.categoryName="jerry,tom,ema"
and
ctries={"Gates","jerry","Jobs","ema"}
I want to check if any ctries is found on p.categoryName. Please help me. Thanks in advance.
To check if any category name is present in ctries try, Intersect
p.categoryName.Intersect(tries).Any()
In my iPhone App.
Problem: When I am trying to get the value from dictionary in model class it is giving me the nil values.
Why this is happening, is this the memory management issue ?
I did this,
I am passing NSDictionary, from my viewController to NSMutableArray Category and from that I am passing it to my Modelclass.
If you want to see the coding,
In my ViewController.m file
[arrayNews convertToNewsArticles];
In my NSMutableArray category I am calling method convertToNewsArticles.
for(NSMutableDictionary *dictionary in self) {
NewsArticle *newsArticle=[[NewsArticle alloc] initWithDictionary:dictionary];
[arrayConverted addObject:newsArticle];
}
I am talking about this dictionary that I am passing.
Here is my Model class
-(NewsArticle*)initWithDictionary:dictionary{
self.title=dictionary[#"title"];
self.author=dictionary[#"author"];
self.urlString=dictionary[#"url"];
return self;
}
Update:
I solved by using IAModelBase class on GitHub.IAModelBase
If it is subclass of NSMutableArray then you can add object like,
[self addObject:newsArticle];
in your for loop and return self will return your final mutable array and you can use it as per desired need!
And refer Apple documentation for more detail. You have to implement some mandatory methods if you want to subclass the NSMutableArray.
When I was trying to convert NSDictionary Objects to Model Objects.
I could not pass the whole dictionary to Model class. Like mentioned in the question.
But instead I used,
IAModel classes
Read the readme file.
Also see the 1st Issue,it is solved.
Pull Issue
I have an initializer that takes an array of Strings as a parameter. Rather than re-write the class and risk breaking things, I'd prefer to feed the initializer what it wants.
I'm trying to extract NSStrings from NSManagedObjects stored in an NSOrderedSet.
Here's what I've tried:
let soundsToPlay = sequenceToPlay.sounds as NSOrderedSet
for element in soundsToPlay {
// this prints out the object in console
print("\(element)")
// this, doesn't give me accessors for the sound object
// print("\(element.fileName)")
}
I'm missing something basic, but I'm not sure what. How would I enumerate the objects in an NSOrderedSet and extract the value of the attributes for the entities contained within the set?
I would suggest reading the documentation on KVC (Key Value Coding) as you can write this as one line of code:
let filenameArray = soundsToPlay.valueForKey("fileName").array()
The call to valueForKey will return an NSOrderedSet of the string and then you can convert that to an array with a call to array()
I figured it out. I was missing a step:
let soundsToPlay = sequenceToPlay.sounds as NSOrderedSet
for element in soundsToPlay {
// I have to tell the compiler what type of thing my thing is
let whatIWantToAccess = element as! MyObjectINeedAccessorsFor
print("\(whatIWantToAccess.fileName)")
}
Thats probably because compiler thinks that "element" is instance of NSManagedObject and it does not have fileName , try explicit type-casting , something like
for element: YourClass in soundsToPlay
I have a feeling there is more than one problem with this code, but my first issue is that my delegate returns nil and I do not know why. First, is my delegate:
import UIKit
//delegate to move information to next screen
protocol userEnteredDataDelegate {
func userDidEnterInformation(info:NSArray)
}
Next, I have a var defined for the delegate and I believe the ? makes it an optional variable? This is defined inside the class
var dataPassDelegate:userEnteredDataDelegate? = nil
Now, after my user has entered information into the fields in the view, I want to add those field values to an array and then pass that array on to the next view where it will be added to. I have pieced this code together from some YouTube examples but I think I am missing a needed part. When do I assign some kind of value to the dataPassDelegate var so it is not nil when the if statement comes? Do I even need that if statement?
if blankData != 1 {
//add code to pass data to next veiw controller
enteredDataArray = [enterDate.text, enterSeason.text, enterSport.text, enterDispTo.text]
//println(enteredDataArray)
self.appIsWorking ()
if (dataPassDelegate != nil) {
let information: NSArray = enteredDataArray
println(information)
dataPassDelegate!.userDidEnterInformation(information)
self.navigationController?.popViewControllerAnimated(true)
} else {
println ("dataPassDelegate = nil")
}
//performSegueWithIdentifier("goToDispenseScreenTwo", sender: self)
activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
}
blankData = 0
}
Your help is appreciated.
A delegate is a pointer to another object that conforms to a particular protocol. Often you use delegates to refine the behavior of your class, or to send back status information o the results of an async network request
When you set your dataPassDelegate delegate is up to you.
What is the object that has the dataPassDelegate property? What object will be serving as the delegate?
You need to create 2 objects (the object that will be serving as the delegate, and the object that has the dataPassDelegate property) and link them up.
We can't tell you when to do that because we don't know what you're trying to do or where these objects will be used.