Search Results

Search found 331 results on 14 pages for 'mutable'.

Page 8/14 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Circular dependency and object creation when attempting DDD

    - by Matthew
    I have a domain where an Organization has People. Organization Entity public class Organization { private readonly List<Person> _people = new List<Person>(); public Person CreatePerson(string name) { var person = new Person(organization, name); _people.Add(person); return person; } public IEnumerable<Person> People { get { return _people; } } } Person Entity public class Person { public Person(Organization organization, string name) { if (organization == null) { throw new ArgumentNullException("organization"); } Organization = organization; Name = name; } public Organization { get; private set; } public Name { get; private set; } } The rule for this relationship is that a Person must belong to exactly one Organization. The invariants I want to guarantee are: A person must have an organization this is enforced via the Person's constuctor An organization must know of its people this is why the Organization has a CreatePerson method A person must belong to only one organization this is why the organization's people list is not publicly mutable (ignoring the casting to List, maybe ToEnumerable can enforce that, not too concerned about it though) What I want out of this is that if a person is created, that the organization knows about its creation. However, the problem with the model currently is that you are able to create a person without ever adding it to the organizations collection. Here's a failing unit-test to describe my problem [Test] public void AnOrganizationMustKnowOfItsPeople() { var organization = new Organization(); var person = new Person(organization, "Steve McQueen"); CollectionAssert.Contains(organization.People, person); } What is the most idiomatic way to enforce the invariants and the circular relationship?

    Read the article

  • Design for object with optional and modifiable attributtes?

    - by Ikuzen
    I've been using the Builder pattern to create objects with a large number of attributes, where most of them are optional. But up until now, I've defined them as final, as recommended by Joshua Block and other authors, and haven't needed to change their values. I am wondering what should I do though if I need a class with a substantial number of optional but non-final (mutable) attributes? My Builder pattern code looks like this: public class Example { //All possible parameters (optional or not) private final int param1; private final int param2; //Builder class public static class Builder { private final int param1; //Required parameters private int param2 = 0; //Optional parameters - initialized to default //Builder constructor public Builder (int param1) { this.param1 = param1; } //Setter-like methods for optional parameters public Builder param2(int value) { param2 = value; return this; } //build() method public Example build() { return new Example(this); } } //Private constructor private Example(Builder builder) { param1 = builder.param1; param2 = builder.param2; } } Can I just remove the final keyword from the declaration to be able to access the attributes externally (through normal setters, for example)? Or is there a creational pattern that allows optional but non-final attributes that would be better suited in this case?

    Read the article

  • Does immutability entirely eliminate the need for locks in multi-processor programming?

    - by GlenPeterson
    Part 1 Clearly Immutability minimizes the need for locks in multi-processor programming, but does it eliminate that need, or are there instances where immutability alone is not enough? It seems to me that you can only defer processing and encapsulate state so long before most programs have to actually DO something. If a program performs actions on multiple processors, something needs to collect and aggregate the results. All this involves multi-process communication before, after, and possibly during some transformations. The start and end state of the machines are different. Can this always be done with no locks just by throwing out each object and creating a new one instead of changing the original (a crude view of immutability)? What cases still require locking? I'm interested in both the theoretical/academic answer and the practical/real-world answer. I know a lot of functional programmers like to talk about "no side effect" but in the "real world" everything has a side effect. Every processor click takes time and electricity and machine resources away from other processes. So I understand that there may be more than one perspective to answer this question from. If immutability is safe, given certain bounds or assumptions, I want to know what the borders of the "safety zone" are exactly. Some examples of possible boundaries: I/O Exceptions/errors Interfaces with programs written in other languages Interfaces with other machines (physical, virtual, or theoretical) Special thanks to @JimmaHoffa for his comment which started this question! Part 2 Multi-processor programming is often used as an optimization technique - to make some code run faster. When is it faster to use locks vs. immutable objects? Given the limits set out in Amdahl's Law, when can you achieve better over-all performance (with or without the garbage collector taken into account) with immutable objects vs. locking mutable ones? Summary I'm combining these two questions into one to try to get at where the bounding box is for Immutability as a solution to threading problems.

    Read the article

  • What's the proper term for a function inverse to a constructor? Deconstructor, destructor, or something else?

    - by Petr Pudlák
    Edit: I'm rephrasing the question a bit. Apparently I caused some confusion because I didn't realize that the term destructor is used in OOP for something quite different - it's a function invoked when an object is being destroyed. In functional programming we (try to) avoid mutable state so there is no such equivalent to it. (I added the proper tag to the question.) Instead, I've seen that the record field for unwrapping a value (especially for single-valued data types such as newtypes) is sometimes called destructor or perhaps deconstructor. For example, let's have (in Haskell): newtype Wrap = Wrap { unwrap :: Int } Here Wrap is the constructor and unwrap is what? I've seen both, for example: ... Most often, one supplies smart constructors and destructors for these to ease working with them. ... at Haskell wiki, or ... The general theme here is to fuse constructor - deconstructor pairs like ... at Haskell wikibook (here it's probably meant in a bit more general sense). The questions are: How do we call unwrap in functional programming? Deconstructor? Destructor? Or by some other term? And to clarify, is this terminology applicable to other functional languages, or is it used just in the Has

    Read the article

  • How do I initialize a Scala map with more than 4 initial elements in Java?

    - by GlenPeterson
    For 4 or fewer elements, something like this works (or at least compiles): import scala.collection.immutable.Map; Map<String,String> HAI_MAP = new Map4<>("Hello", "World", "Happy", "Birthday", "Merry", "XMas", "Bye", "For Now"); For a 5th element I could do this: Map<String,String> b = HAI_MAP.$plus(new Tuple2<>("Later", "Aligator")); But I want to know how to initialize an immutable map with 5 or more elements and I'm flailing in Type-hell. Partial Solution I thought I'd figure this out quickly by compiling what I wanted in Scala, then decompiling the resultant class files. Here's the scala: object JavaMapTest { def main(args: Array[String]) = { val HAI_MAP = Map(("Hello", "World"), ("Happy", "Birthday"), ("Merry", "XMas"), ("Bye", "For Now"), ("Later", "Aligator")) println("My map is: " + HAI_MAP) } } But the decompiler gave me something that has two periods in a row and thus won't compile (I don't think this is valid Java): scala.collection.immutable.Map HAI_MAP = (scala.collection.immutable.Map) scala.Predef..MODULE$.Map().apply(scala.Predef..MODULE$.wrapRefArray( scala.Predef.wrapRefArray( (Object[])new Tuple2[] { new Tuple2("Hello", "World"), new Tuple2("Happy", "Birthday"), new Tuple2("Merry", "XMas"), new Tuple2("Bye", "For Now"), new Tuple2("Later", "Aligator") })); I'm really baffled by the two periods in this: scala.Predef..MODULE$ I asked about it on #java on Freenode and they said the .. looked like a decompiler bug. It doesn't seem to want to compile, so I think they are probably right. I'm running into it when I try to browse interfaces in IntelliJ and am just generally lost. Based on my experimentation, the following is valid: Tuple2[] x = new Tuple2[] { new Tuple2<String,String>("Hello", "World"), new Tuple2<String,String>("Happy", "Birthday"), new Tuple2<String,String>("Merry", "XMas"), new Tuple2<String,String>("Bye", "For Now"), new Tuple2<String,String>("Later", "Aligator") }; scala.collection.mutable.WrappedArray<Tuple2> y = scala.Predef.wrapRefArray(x); There is even a WrappedArray.toMap() method but the types of the signature are complicated and I'm running into the double-period problem there too when I try to research the interfaces from Java.

    Read the article

  • What's the proper term for a function inverse to a constructor - to unwrap a value from a data type?

    - by Petr Pudlák
    Edit: I'm rephrasing the question a bit. Apparently I caused some confusion because I didn't realize that the term destructor is used in OOP for something quite different - it's a function invoked when an object is being destroyed. In functional programming we (try to) avoid mutable state so there is no such equivalent to it. (I added the proper tag to the question.) Instead, I've seen that the record field for unwrapping a value (especially for single-valued data types such as newtypes) is sometimes called destructor or perhaps deconstructor. For example, let's have (in Haskell): newtype Wrap = Wrap { unwrap :: Int } Here Wrap is the constructor and unwrap is what? The questions are: How do we call unwrap in functional programming? Deconstructor? Destructor? Or by some other term? And to clarify, is this/other terminology applicable to other functional languages, or is it used just in the Haskell? Perhaps also, is there any terminology for this in general, in non-functional languages? I've seen both terms, for example: ... Most often, one supplies smart constructors and destructors for these to ease working with them. ... at Haskell wiki, or ... The general theme here is to fuse constructor - deconstructor pairs like ... at Haskell wikibook (here it's probably meant in a bit more general sense), or newtype DList a = DL { unDL :: [a] -> [a] } The unDL function is our deconstructor, which removes the DL constructor. ... in The Real World Haskell.

    Read the article

  • FP for simulation and modelling

    - by heaptobesquare
    I'm about to start a simulation/modelling project. I already know that OOP is used for this kind of projects. However, studying Haskell made me consider using the FP paradigm for modelling a system of components. Let me elaborate: Let's say I have a component of type A, characterised by a set of data (a parameter like temperature or pressure,a PDE and some boundary conditions,etc.) and a component of type B, characterised by a different set of data(different or same parameter, different PDE and boundary conditions). Let's also assume that the functions/methods that are going to be applied on each component are the same (a Galerkin method for example). If I were to use an OOP approach, I would create two objects that would encapsulate each type's data, the methods for solving the PDE(inheritance would be used here for code reuse) and the solution to the PDE. On the other hand, if I were to use an FP approach, each component would be broken down to data parts and the functions that would act upon the data in order to get the solution for the PDE. This approach seems simpler to me assuming that linear operations on data would be trivial and that the parameters are constant. What if the parameters are not constant(for example, temperature increases suddenly and therefore cannot be immutable)? In OOP, the object's (mutable) state can be used. I know that Haskell has Monads for that. To conclude, would implementing the FP approach be actually simpler,less time consuming and easier to manage (add a different type of component or new method to solve the pde) compared to the OOP one? I come from a C++/Fortran background, plus I'm not a professional programmer, so correct me on anything that I've got wrong.

    Read the article

  • Functional Programming, JavaScript and UI - some neophyte questions

    - by jamesson
    This has been discussed in other threads, however I am hoping for some comments relevant to UI and an explanation of some vitriol I had flung my way in a Certain IRC Channel Which shall remain nameless. In the discussion here, the comments in the accepted answer suggest that I approach the given code from a functional perspective, which was new to me at the time. Wikipedia said, among other things, that FP "avoids state and mutable data", which includes according to the discussion global vars. Now, being that I am already pretty far along in my project I am not going to learn FP before I finish, but... How is it possible to avoid global vars if, for instance, I have a UI whose entire functionality changes if a mousebutton is down? I have a number of things like this. Why was there a strong negative reaction in the Certain IRC channel to implementing FP in JS? When I Brought up what seemed to me to be supportive comments by Crockford, people got even madder. Now, this being IRC there is no rep system, but they at least gave indication of having read TGP (which I haven't gotten to yet) so I'm assuming they're not idiots. Many thanks in advance Joe

    Read the article

  • Are there legitimate reasons for returning exception objects instead of throwing them?

    - by stakx
    This question is intended to apply to any OO programming language that supports exception handling; I am using C# for illustrative purposes only. Exceptions are usually intended to be raised when an problem arises that the code cannot immediately handle, and then to be caught in a catch clause in a different location (usually an outer stack frame). Q: Are there any legitimate situations where exceptions are not thrown and caught, but simply returned from a method and then passed around as error objects? This question came up for me because .NET 4's System.IObserver<T>.OnError method suggests just that: exceptions being passed around as error objects. Let's look at another scenario, validation. Let's say I am following conventional wisdom, and that I am therefore distinguishing between an error object type IValidationError and a separate exception type ValidationException that is used to report unexpected errors: partial interface IValidationError { } abstract partial class ValidationException : System.Exception { public abstract IValidationError[] ValidationErrors { get; } } (The System.Component.DataAnnotations namespace does something quite similar.) These types could be employed as follows: partial interface IFoo { } // an immutable type partial interface IFooBuilder // mutable counterpart to prepare instances of above type { bool IsValid(out IValidationError[] validationErrors); // true if no validation error occurs IFoo Build(); // throws ValidationException if !IsValid(…) } Now I am wondering, could I not simplify the above to this: partial class ValidationError : System.Exception { } // = IValidationError + ValidationException partial interface IFoo { } // (unchanged) partial interface IFooBuilder { bool IsValid(out ValidationError[] validationErrors); IFoo Build(); // may throw ValidationError or sth. like AggregateException<ValidationError> } Q: What are the advantages and disadvantages of these two differing approaches?

    Read the article

  • Making a class pseudo-immutable by setting a flag

    - by scott_fakename
    I have a java project that involves building some pretty complex objects. There are quite a lot (dozens) of different ones and some of them have a HUGE number of parameters. They also need to be immutable. So I was thinking the builder pattern would work, but it ends up require a lot of boilerplate. Another potential solution I thought of was to make a mutable class, but give it a "frozen" flag, a-la ruby. Here is a simple example: public class EqualRule extends Rule { private boolean frozen; private int target; public EqualRule() { frozen = false; } public void setTarget(int i) { if (frozen) throw new IllegalStateException( "Can't change frozen rule."); target = i; } public int getTarget() { return target; } public void freeze() { frozen = true; } @Override public boolean checkRule(int i) { return (target == i); } } and "Rule" is just an abstract class that has an abstract "checkRule" method. This cuts way down on the number of objects I need to write, while also giving me an object that becomes immutable for all intents and purposes. This kind of act like the object was its own Builder... But not quite. I'm not too excited, however, about having an immutable being disguised as a bean however. So I had two questions: 1. Before I go too far down this path, are there any huge problems that anyone sees right off the bat? For what it's worth, it is planned that this behavior will be well documented... 2. If so, is there a better solution? Thanks

    Read the article

  • Recommended design pattern for object with optional and modifiable attributtes? [on hold]

    - by Ikuzen
    I've been using the Builder pattern to create objects with a large number of attributes, where most of them are optional. But up until now, I've defined them as final, as recommended by Joshua Block and other authors, and haven't needed to change their values. I am wondering what should I do though if I need a class with a substantial number of optional but non-final (mutable) attributes? My Builder pattern code looks like this: public class Example { //All possible parameters (optional or not) private final int param1; private final int param2; //Builder class public static class Builder { private final int param1; //Required parameters private int param2 = 0; //Optional parameters - initialized to default //Builder constructor public Builder (int param1) { this.param1 = param1; } //Setter-like methods for optional parameters public Builder param2(int value) { param2 = value; return this; } //build() method public Example build() { return new Example(this); } } //Private constructor private Example(Builder builder) { param1 = builder.param1; param2 = builder.param2; } } Can I just remove the final keyword from the declaration to be able to access the attributes externally (through normal setters, for example)? Or is there a creational pattern that allows optional but non-final attributes that would be better suited in this case?

    Read the article

  • Series of abstract classes and NHibernate

    - by Chris Cowdery-Corvan
    Hello, and first off thanks for your time to look at this. For a research project I'm working on, I have a somewhat complex design (which I've been given) to persist to a database via NHibernate. Here's an example of the class hierarchy: TransitStrategy, TransportationCompany and TransportationLocation are all abstract classes. The XML configuration I have is presently: <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Vacationizer" namespace="Vacationizer.Domain.Transit"> <class name="TransitStrategy"> <id name="TransitStrategyId"> <generator class="guid" /> </id> <property name="Restrictions" /> <joined-subclass name="Flight" table="Flight_TransitStrategy"> <key column="TransitStrategyId" /> <property name="DepartingAirport" /> <property name="ArrivingAirport" /> <property name="Airline" /> <property name="FlightNumber" /> <property name="FlightArrivalTime" /> <property name="FlightDepartureTime" /> </joined-subclass> <joined-subclass name="RentalCar" table="RentalCar_TransitStrategy"> <key column="TransitStrategyId" /> <property name="RentalCarBranch" /> <property name="CarMake" /> <property name="CarModel" /> <property name="CarYear" /> <property name="CarColor" /> <property name="RentalBegins" /> <property name="RentalEnds" /> </joined-subclass> </class> <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Vacationizer" namespace="Vacationizer.Domain.Transit"> <class name="TransportationCompany"> <id name="TransportationCompanyId"> <generator class="guid" /> </id> <property name="Name" /> <property name="Reviews" /> <property name="Website" /> <property name="Photo" /> <joined-subclass name="Airline" table="Airline_TransportationCompany"> <key column="TransportationLocationId" /> </joined-subclass> <joined-subclass name="RentalCarAgency" table="RentalCarAgency_TransportationCompany"> <key column="TransportationLocationId" /> </joined-subclass> </class> <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Vacationizer" namespace="Vacationizer.Domain.Transit"> <class name="TransportationLocation"> <id name="TransportationLocationId"> <generator class="guid" /> </id> <property name="Name" /> <property name="Image" /> <property name="Geolocation" /> <property name="Reviews" /> <!-- <property name="HoursOpen" />--> <property name="PhoneNumber" /> <property name="FaxNumber" /> <joined-subclass name="Airport" table="Airport_TransportationLocation"> <key column="TransportationLocationId" /> <property name="AirportCode" /> <property name="Website" /> </joined-subclass> <joined-subclass name="RentalCarBranch" table="RentalCarBranch_TransportationLocation"> <key column="TransitStrategyId" /> <property name="Agency" /> </joined-subclass> </class> However, whenever I try to use this schema I get this error/stack trace: ------ Test started: Assembly: Vacationizer.Tests.dll ------ TestCase 'M:Vacationizer.Tests.VacationRepository_Fixture.TestFixtureSetUp' failed: Could not compile the mapping document: Vacationizer.Mappings.TransitStrategy.hbm.xml NHibernate.MappingException: Could not compile the mapping document: Vacationizer.Mappings.TransitStrategy.hbm.xml ---> NHibernate.MappingException: Problem trying to set property type by reflection ---> NHibernate.MappingException: class Vacationizer.Domain.Transit.RentalCar, Vacationizer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null not found while looking for property: RentalCarBranch ---> NHibernate.PropertyNotFoundException: Could not find a getter for property 'RentalCarBranch' in class 'Vacationizer.Domain.Transit.RentalCar' at NHibernate.Properties.BasicPropertyAccessor.GetGetter(Type type, String propertyName) at NHibernate.Util.ReflectHelper.ReflectedPropertyClass(String className, String name, String accessorName) --- End of inner exception stack trace --- at NHibernate.Util.ReflectHelper.ReflectedPropertyClass(String className, String name, String accessorName) at NHibernate.Mapping.SimpleValue.SetTypeUsingReflection(String className, String propertyName, String accesorName) --- End of inner exception stack trace --- at NHibernate.Mapping.SimpleValue.SetTypeUsingReflection(String className, String propertyName, String accesorName) at NHibernate.Cfg.XmlHbmBinding.ClassBinder.CreateProperty(IValue value, String propertyName, String className, XmlNode subnode, IDictionary`2 inheritedMetas) at NHibernate.Cfg.XmlHbmBinding.ClassBinder.PropertiesFromXML(XmlNode node, PersistentClass model, IDictionary`2 inheritedMetas, UniqueKey uniqueKey, Boolean mutable, Boolean nullable, Boolean naturalId) at NHibernate.Cfg.XmlHbmBinding.JoinedSubclassBinder.HandleJoinedSubclass(PersistentClass model, XmlNode subnode, IDictionary`2 inheritedMetas) at NHibernate.Cfg.XmlHbmBinding.ClassBinder.PropertiesFromXML(XmlNode node, PersistentClass model, IDictionary`2 inheritedMetas, UniqueKey uniqueKey, Boolean mutable, Boolean nullable, Boolean naturalId) at NHibernate.Cfg.XmlHbmBinding.RootClassBinder.Bind(XmlNode node, HbmClass classSchema, IDictionary`2 inheritedMetas) at NHibernate.Cfg.XmlHbmBinding.MappingRootBinder.AddRootClasses(XmlNode parentNode, IDictionary`2 inheritedMetas) at NHibernate.Cfg.XmlHbmBinding.MappingRootBinder.Bind(XmlNode node) at NHibernate.Cfg.Configuration.AddValidatedDocument(NamedXmlDocument doc) --- End of inner exception stack trace --- at NHibernate.Cfg.Configuration.LogAndThrow(Exception exception) at NHibernate.Cfg.Configuration.AddValidatedDocument(NamedXmlDocument doc) at NHibernate.Cfg.Configuration.ProcessMappingsQueue() at NHibernate.Cfg.Configuration.AddDocumentThroughQueue(NamedXmlDocument document) at NHibernate.Cfg.Configuration.AddXmlReader(XmlReader hbmReader, String name) at NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name) at NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly) at NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly) at NHibernate.Cfg.Configuration.AddAssembly(String assemblyName) at NHibernate.Cfg.Configuration.DoConfigure(IHibernateConfiguration hc) at NHibernate.Cfg.Configuration.Configure() VacationRepository_Fixture.cs(24,0): at Vacationizer.Tests.VacationRepository_Fixture.TestFixtureSetUp() 0 passed, 1 failed, 0 skipped, took 8.38 seconds (Ad hoc). Any ideas on how I can implement this differently? Thanks very much!

    Read the article

  • How to scroll to the bottom of a UITableView on the iPhone before the view appears

    - by acqu13sce
    I have a UITableView that is populated with cells of a variable height. I would like the table to scroll to the bottom when the view is pushed into view. I currently have the following function NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[log count]-1 inSection:0]; [self.table scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO]; log is a mutable array containing the objects that make up the content of each cell. The above code works fine in viewDidAppear however this has the unfortunate side effect of displaying the top of the table when the view first appears and then jumping to the bottom. I would prefer it if the table view could be scrolled to the bottom before it appears. I tried the scroll in viewWillAppear and viewDidLoad but in both cases the data has not been loaded into the table yet and both throw an exception. Any guidance would be much appreciated, even if it's just a case of telling me what I have is all that is possible.

    Read the article

  • Overwrite msg in mirth

    - by Ryan H
    I have two destinations now and the first calls a SOAP webservice. I want to take the response of that destination by: msg = new XML(responseMap.get('Destination1').getMessage()); and convert it to a mutable XML object. Doing: logger.error(msg); <S:Body><PRPA_IN201306UV02> ... </PRPA_IN201306UV02></S:Body> Shows the valid msg as I want it, but when I do: msg['S:Body'] it returns nothing. Any suggestions would help.

    Read the article

  • Objective C defining UIColor constants

    - by futureelite7
    Hi, I have a iPhone application with a few custom-defined colors for my theme. Since these colors will be fixed for my UI, I would like to define the colors in a class to be included (Constants.h and Constants.m). How do I do that? (Simply defining them does not work because UIColors are mutable, and would cause errors - Initalizer not constant). /* Constants.h */ extern UIColor *test; /* Constants.m */ UIColor *test = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0]; Thanks!

    Read the article

  • Observing model changes with Cocoa Bindings and NSArrayController

    - by jbrennan
    I've got an NSArrayController bound to a mutable array in my controller, which manages an array of my model objects. The array controller is bound to my UI. It works well. Now I'm trying to manually observe when a value changes in my model in my controller class (basically I'm marking the changed model as "needsToSave" for later on, but there are a few other tasks I have when it changes). I've read up on KVO but I'm not entirely sure what I need to be observing... The NSArrayController? The array of objects? each model object itself? Confusion. Any pointers would be very helpful. Thanks in advance!

    Read the article

  • Issue passing NSMutableDictionary to a method

    - by roswell
    Hello all, I've got a chunk of code that's passing an NSMutableDictionary (amongst other things) to a method in another class: [self.shuttle makeAPICallAndReturnResultsUsingMode:@"login" module:@"login" query:credentials]; The NSMutableArray credentials is previously defined like this: NSMutableDictionary *credentials = [[NSMutableDictionary alloc] init]; [credentials setObject:username forKey:@"username"]; [credentials setObject:password forKey:@"password"]; The method that receives it looks like this: -(id)makeAPICallAndReturnResultsUsingMode:(NSString *)mode module:(NSString *)module query:(NSMutableDictionary *)query The code works fine up until this point within the above method: [query setObject:self.sessionID forKey:@"session_id"]; At this point, the application terminates -- the console informs me of this exception: * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSCFDictionary setObject:forKey:]: method sent to an uninitialized mutable dictionary object' This leads me to believe that I must initialize NSMutableDictionary in some way in my new method before I can access it, but I have no idea how. Any advice?

    Read the article

  • iphone - mutableArray cannot store nil objects

    - by Mike
    I have a mutable array that is retained and storing several objects. At some point, one object may become nil. When this happens the app will crash, because arrays cannot have nil objects. Imagine something like [object1, object2, object3, nil]; then, object2 = nil [object1, nil, object3, nil]; that is not possible because nil is the end of array marker. So, how can I solve that? thanks for any help.

    Read the article

  • NSNumberFormatter crashing iPhone SDK 4.0b2

    - by Ward
    Hey there, I've got an app that's been in the app store for a while and functions perfectly on OS 3.1 - 3.13. However, when tested on 4.0b2 I noticed that it crashes in the same place every time, but only on the device, never on the simulator. I'm using a 3GS to test. On loadView I initialize an NSNumberFormatter object which is declared and retained in the interface so I have access to it everywhere. In my method I call it several times to convert string values into nsnumbers to be stored in a mutable dictionary. Here's an example: [myDictionary setObject:[myStyleFormatter numberFromString:@"1"] forKey:@"hours"]; [myDictionary setObject:[myStyleFormatter numberFromString:@"30"] forKey:@"minutes"]; [myDictionary setObject:[myStyleFormatter numberFromString:@"10"] forKey:@"seconds"]; For some reason it crashes as soon as it tries to set hours. The error is "attempt to insert nil value (key: hours)" Have I been doing something wrong all along? Has the api changed for 4.0b2? Thanks, Howie

    Read the article

  • Building big, immutable objects without constructors having long parameter lists

    - by Malax
    Hi StackOverflow! I have some big (more than 3 fields) Objects which can and should be immutable. Every time I run into that case i tend to create constructor abominations with long parameter lists. It doesn't feel right, is hard to use and readability suffers. It is even worse if the fields are some sort of collection type like lists. A simple addSibling(S s) would ease the object creation so much but renders the object mutable. What do you guys use in such cases? I'm on Scala and Java, but i think the problem is language agnostic as long as the language is object oriented. Solutions I can think of: "Constructor abominations with long parameter lists" The Builder Pattern Thanks for your input!

    Read the article

  • C++ Mutexes and STL Lists Across Subclasses

    - by Genesis
    I am currently writing a multi-threaded C++ server using Poco and am now at the point where I need to be keeping information on which users are connected, how many connections each of them have, and given it is a proxy server, where each of those connections are proxying through to. For this purpose I have created a ServerStats class which holds an STL list of ServerUser objects. The ServerStats class includes functions which can add and remove objects from the list as well as find a user in the list an return a pointer to them so I can access member functions within any given ServerUser object in the list. The ServerUser class contains an STL list of ServerConnection objects and much like the ServerStats class it contains functions to add, remove and find elements within this list. Now all of the above is working but I am now trying to make it threadsafe. I have defined a Poco::FastMutex within the ServerStats class and can lock/unlock this in the appropriate places so that STL containers are not modified at the same time as being searched for example. I am however having an issue setting up mutexes within the ServerUser class and am getting the following compiler error: /root/poco/Foundation/include/Poco/Mutex.h: In copy constructor âServerUser::ServerUser(const ServerUser&)â: src/SocksServer.cpp:185: instantiated from âvoid __gnu_cxx::new_allocator<_Tp::construct(_Tp*, const _Tp&) [with _Tp = ServerUser]â /usr/include/c++/4.4/bits/stl_list.h:464: instantiated from âstd::_List_node<_Tp* std::list<_Tp, _Alloc::_M_create_node(const _Tp&) [with _Tp = ServerUser, _Alloc = std::allocator]â /usr/include/c++/4.4/bits/stl_list.h:1407: instantiated from âvoid std::list<_Tp, _Alloc::_M_insert(std::_List_iterator<_Tp, const _Tp&) [with _Tp = ServerUser, _Alloc = std::allocator]â /usr/include/c++/4.4/bits/stl_list.h:920: instantiated from âvoid std::list<_Tp, _Alloc::push_back(const _Tp&) [with _Tp = ServerUser, _Alloc = std::allocator]â src/SocksServer.cpp:301: instantiated from here /root/poco/Foundation/include/Poco/Mutex.h:164: error: âPoco::FastMutex::FastMutex(const Poco::FastMutex&)â is private src/SocksServer.cpp:185: error: within this context In file included from /usr/include/c++/4.4/x86_64-linux-gnu/bits/c++allocator.h:34, from /usr/include/c++/4.4/bits/allocator.h:48, from /usr/include/c++/4.4/string:43, from /root/poco/Foundation/include/Poco/Bugcheck.h:44, from /root/poco/Foundation/include/Poco/Foundation.h:147, from /root/poco/Net/include/Poco/Net/Net.h:45, from /root/poco/Net/include/Poco/Net/TCPServerParams.h:43, from src/SocksServer.cpp:1: /usr/include/c++/4.4/ext/new_allocator.h: In member function âvoid __gnu_cxx::new_allocator<_Tp::construct(_Tp*, const _Tp&) [with _Tp = ServerUser]â: /usr/include/c++/4.4/ext/new_allocator.h:105: note: synthesized method âServerUser::ServerUser(const ServerUser&)â first required here src/SocksServer.cpp: At global scope: src/SocksServer.cpp:118: warning: âstd::string getWord(std::string)â defined but not used make: * [/root/poco/SocksServer/obj/Linux/x86_64/debug_shared/SocksServer.o] Error 1 The code for the ServerStats, ServerUser and ServerConnection classes is below: class ServerConnection { public: bool continue_connection; int bytes_in; int bytes_out; string source_address; string destination_address; ServerConnection() { continue_connection = true; } ~ServerConnection() { } }; class ServerUser { public: string username; int connection_count; string client_ip; ServerUser() { } ~ServerUser() { } ServerConnection* addConnection(string source_address, string destination_address) { //FastMutex::ScopedLock lock(_connection_mutex); ServerConnection connection; connection.source_address = source_address; connection.destination_address = destination_address; client_ip = getWord(source_address, ":"); _connections.push_back(connection); connection_count++; return &_connections.back(); } void removeConnection(string source_address) { //FastMutex::ScopedLock lock(_connection_mutex); for(list<ServerConnection>::iterator it = _connections.begin(); it != _connections.end(); it++) { if(it->source_address == source_address) { it = _connections.erase(it); connection_count--; } } } void disconnect() { //FastMutex::ScopedLock lock(_connection_mutex); for(list<ServerConnection>::iterator it = _connections.begin(); it != _connections.end(); it++) { it->continue_connection = false; } } list<ServerConnection>* getConnections() { return &_connections; } private: list<ServerConnection> _connections; //UNCOMMENTING THIS LINE BREAKS IT: //mutable FastMutex _connection_mutex; }; class ServerStats { public: int current_users; ServerStats() { current_users = 0; } ~ServerStats() { } ServerUser* addUser(string username) { FastMutex::ScopedLock lock(_user_mutex); for(list<ServerUser>::iterator it = _users.begin(); it != _users.end(); it++) { if(it->username == username) { return &(*it); } } ServerUser newUser; newUser.username = username; _users.push_back(newUser); current_users++; return &_users.back(); } void removeUser(string username) { FastMutex::ScopedLock lock(_user_mutex); for(list<ServerUser>::iterator it = _users.begin(); it != _users.end(); it++) { if(it->username == username) { _users.erase(it); current_users--; break; } } } ServerUser* getUser(string username) { FastMutex::ScopedLock lock(_user_mutex); for(list<ServerUser>::iterator it = _users.begin(); it != _users.end(); it++) { if(it->username == username) { return &(*it); } } return NULL; } private: list<ServerUser> _users; mutable FastMutex _user_mutex; }; Now I have never used C++ for a project of this size or mutexes for that matter so go easy please :) Firstly, can anyone tell me why the above is causing a compiler error? Secondly, can anyone suggest a better way of storing the information I require? Bear in mind that I need to update this info whenever connections come or go and it needs to be global to the whole server.

    Read the article

  • Building big, immutable objects without using constructors having long parameter lists

    - by Malax
    Hi StackOverflow! I have some big (more than 3 fields) Objects which can and should be immutable. Every time I run into that case i tend to create constructor abominations with long parameter lists. It doesn't feel right, is hard to use and readability suffers. It is even worse if the fields are some sort of collection type like lists. A simple addSibling(S s) would ease the object creation so much but renders the object mutable. What do you guys use in such cases? I'm on Scala and Java, but i think the problem is language agnostic as long as the language is object oriented. Solutions I can think of: "Constructor abominations with long parameter lists" The Builder Pattern Thanks for your input!

    Read the article

  • To store images from UIGetScreenImage() in NSMutable Array

    - by sujyanarayan
    Hi, I'm getting images from UIGetScreenImage() and storing directly in mutable array like:- image = [UIImage imageWithScreenContents]; [array addObject:image]; [image release]; I've set this code in timer so I cant use UIImagePNGRepresentation() to store as NSData as it reduces the performance. I want to use this array directly after sometime i.e after capturing 1000 images in 100 seconds. When I use the code below:- UIImage *im = [[UIImage alloc] init]; im = [array objectAtIndex:i]; UIImageWriteToSavedPhotosAlbum(im, nil, nil, nil); the application crashes. And I dont want to use UIImagePNG or JPGRepresentation() in timer as it reduces performance. My problem is how to use this array so that it is converted into image. If anybody has idea related to it please share with me. Thanks in Advance.

    Read the article

  • BindingList projection wrapper

    - by Groo
    Is there a simple way to create a BindingList wrapper (with projection), which would update as the original list updates? For example, let's say I have a mutable list of numbers, and I want to represent them as hex strings in a ComboBox. Using this wrapper I could do something like this: BindingList<int> numbers = data.GetNumbers(); comboBox.DataSource = Project(numbers, i => string.Format("{0:x}", i)); I could wrap the list into a new BindingList, handle all source events, update the list and fire these events again, but I feel that there is a simpler way already.

    Read the article

  • Issue Passing NSMutableDictionary to Method

    - by roswell
    Hello all, I'm trying some basic iPhone programming -- all has been going well but recently I've hit a bit of a roadblock. I've got a chunk of code that's passing an NSMutableDictionary (amongst other things) to a method in another class: [self.shuttle makeAPICallAndReturnResultsUsingMode:@"login" module:@"login" query:credentials]; The NSMutableArray credentials is previously defined a bit above as such: NSMutableDictionary *credentials = [[NSMutableDictionary alloc] init]; [credentials setObject:username forKey:@"username"]; [credentials setObject:password forKey:@"password"]; The method that receives it looks like such: -(id)makeAPICallAndReturnResultsUsingMode:(NSString *)mode module:(NSString *)module query:(NSMutableDictionary *)query From debugging I have determined that the code works fine up until this point within the above method: [query setObject:self.sessionID forKey:@"session_id"]; At this point, the application terminates -- the Console informs me of this exception: * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSCFDictionary setObject:forKey:]: method sent to an uninitialized mutable dictionary object' This leads me to believe that I must initialize NSMutableDictionary in some way in my new method before I can access it, but I have no idea how. Any advice?

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14  | Next Page >